解题思路:
回溯
提交代码:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> curComb = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
curComb.add(i+1);
makeCombination(curComb, n, k, ans);
curComb.remove(curComb.size()-1);
}
return ans;
}
public void makeCombination(List<Integer> curComb, int n, int k, List<List<Integer>> ans) {
if (curComb.size() == k) {
List<Integer> tmp=new ArrayList<Integer>();
tmp.addAll(curComb);
ans.add(tmp);
return;
}
for (int i = curComb.get(curComb.size()-1); i < n; i++) {
curComb.add(i+1);
makeCombination(curComb, n, k, ans);
curComb.remove(curComb.size()-1);
}
}
}
运行结果: