Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (n <= 0 || k <= 0 || k > n) {
return results;
}
List<Integer> list = new ArrayList<Integer>();
helper(n, k, results, list, 1, 0);
return results;
}
public void helper(int n, int k, List<List<Integer>> results, List<Integer> list, int m, int d){
if(d == k){
results.add(new ArrayList<Integer>(list));
return;
}
for(int i = m; i <= n; i++){
list.add(i);
helper(n, k, results, list, i + 1, d + 1);
list.remove(list.size() - 1);
}
}
}
Runtime: 26 ms, faster than 55.90% of Java online submissions for Combinations.
总结
- 发现ArrayList比LinkedList快一点
- results.add(new ArrayList(list));这句话要注意,results回溯的时候不会回退,因为不存在弹栈,是指针,地址或者说引用。所以当list加到results里时,list继续调用时被更改,所以results里的list也一直在变。状态为:12然后 13 13; 23 23 23…最后list 回退为空。results里也全变为空了。