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], ]
思路:本题的是一个典型的回溯剪枝问题,比如例子程序[2,4],那么[4,2]就剪了即第i个数,必须在比前i-1个数大的里面选。如n=5,k=3;
[1,2,3],[1,2,4] ,[1,2,5],[1,3,4],[1,3,5],[1,4,5]
[2,3,4],[2,3,5] ,[2,4,5]
[3,4,5]
其实就是排列组合中的C(n,k),每选一个k的个数减1,直到k=0,将这个list,加入到lists中。递归用在产生list的过程中。因为如果不用递归,用循环的话,如果k=10就要写10重循环,递归看起来比较整齐,易懂。
比如上例到[1,2,5]的时候,5已结是最大了,第三位已结没法继续往下了,就要向前面回溯,改变第二位变成3.然后依次下去,这就是回溯
代码如下(已通过leetcode)
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> relists=new ArrayList<List<Integer>>();
List<Integer> temp=new ArrayList<Integer>();
genarateLists(relists,temp,1,n,k);
return relists;
}
private void genarateLists(List<List<Integer>> relists, List<Integer> temp, int start, int end, int k) {
// TODO Auto-generated method stub
if(k==0) {
relists.add(temp);
}
for(int i=start;i<=end;i++){
List<Integer> temp2=new ArrayList<Integer>(temp);
temp2.add(i);
genarateLists(relists, temp2, i+1, end, k-1);
}
}
}