题目描述:
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
比较简单,但是为什么,我将 result.add(new ArrayList(tem));换成这个result.add(tem),难道是因为使用了一个内存空间,导致后面加入的均是一个tem?所以需要另外新建一个tem,这样就不会冲突了??
就是空的呢??
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
//k个数字,和为n
List<List<Integer>> result = new ArrayList<>();
int[] nums = {1,2,3,4,5,6,7,8,9};
List<Integer> tem = new ArrayList<>();
getcombinatisonSum3(nums, 0, k, result, tem, n);
return result;
}
public static void getcombinatisonSum3(int nums[],int start,int k ,List<List<Integer>> result, List<Integer> tem,int target){
if(k == tem.size() && target == 0){
result.add(new ArrayList<Integer>(tem));
return ;
}
for (int i = start; i < 9; i++) {
tem.add(nums[i]);
getcombinatisonSum3(nums, i +1, k, result, tem, target - nums[i]);
tem.remove(tem.size() - 1);
}
}
}