• Combinations


    Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

    For example,
    If n = 4 and k = 2, a solution is:

    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]
    这道题完全是凭着感觉A出来的
     1 public class Solution {
     2     private List<List<Integer>> result = new ArrayList<List<Integer>>();
     3     
     4     public List<List<Integer>> combine(int n, int k) {
     5         List<Integer> cur = new ArrayList<Integer>();
     6         
     7         getResult(cur, 1, 0, k, n);
     8        
     9         return result;
    10     }
    11     public void getResult(List<Integer> cur, int start, int dep, int depMax, int end){
    12         if(dep == depMax){
    13             List<Integer> temp = new ArrayList<Integer>(cur);
    14             result.add(temp);
    15         }else{
    16             for(int i = start; i <= end; i++){
    17                 cur.add(i);
    18                 getResult(cur, i + 1, dep + 1, depMax, end);
    19                 cur.remove(cur.size() - 1);
    20             }
    21         }
    22     }
    23 }
  • 相关阅读:
    break return continue
    爬虫---请求
    pycharm加开头注释
    爬虫---入门
    pip
    XML基础
    英语
    布局
    adobe
    StackOverflow
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4216011.html
Copyright © 2020-2023  润新知