Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
这是一道跟oj46很像的题目,因为它们用的都是回溯法。具体的思路是:一开始设定子列表的长度为k,添加一个后就k-1,直到k=0表示一个子列表完成,将它添加到结果列表中;如果k!=0,添加新元素的位置就要后移。其余的一些细节写在注释里
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
List<Integer> temp=new ArrayList<Integer>();
Process(result,temp,1,n,k);
return result;
}
private void Process(List<List<Integer>> result,List<Integer> temp,int start,int n,int k){
if(k == 0){
//直接写temp不行?直接temp为空,因为后面要用remove对temp进行修改,所以这里需要add的是temp拷贝一份的结果,而不是直接temp
result.add(new ArrayList<Integer>(temp));
}
else{
for(int i=start;i<=n;i++){
temp.add(i);
Process(result,temp,i+1,n,k-1);//传过去的是start+1的话出来1234223432344234这样
//remove的原因:在得到[1,2]之后想要得到[1,3]就不需要另外新建list,只需要remove'2',再加上3即可,这也就是上面直接add(temp)只会得到空列表
temp.remove(temp.size()-1);???????[[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,2,3],[1,2,3,4,2,3,4],[1,2,3,4,2,3,4,3,4]]
}
}
}
}