题意:给定n和k,从1到n中选k个数,存到结果中.
回溯,每次选择一个数字插入,检查是否满足k个数,满足加入ans,返回结果
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if(k == 0){
return ans;
}
cal(ans, new ArrayList<Integer>(), n, k, 0, 0);
return ans;
}
public void cal(List<List<Integer>> ans, ArrayList<Integer> list, int n, int k, int curPo, int preNum){
if(curPo == k){
ans.add(new ArrayList<Integer>(list));
return;
}
for(int i = preNum + 1; i <= n; ++i){
list.add(i);
cal(ans, list, n, k, curPo + 1, i);
list.remove(list.size() - 1);
}
}