77. 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],
]

 本题也是采用回溯法,做法与之前的比较类似,代码如下:

 1 public class Solution {
 2     public List<List<Integer>> combine(int n, int k) {
 3         List<List<Integer>> res= new ArrayList<>();
 4         backtracking(res,new ArrayList<Integer>(),n,k,1);
 5         return res;
 6     }
 7     public void backtracking(List<List<Integer>> res,List<Integer> list,int n,int k,int cur){
 8         if(k==0) res.add(new ArrayList<Integer>(list));
 9         else if(k<0) return;
10         else if(k>0){
11             for(int i=cur;i<=n;i++){
12                 list.add(i);
13                 backtracking(res,list,n,k-1,i+1);
14                 list.remove(list.size()-1);
15             }
16         }
17     }
18 }
原文地址:https://www.cnblogs.com/codeskiller/p/6390414.html