216. Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
题解:
推荐先看一下:
和前面几题不同的就是这次对于集合是固定的,是 [1,2,3,4,5,6,7,8,9] ,要求的和为 n 的集合的大小必须为 k
所以对于固定的集合,正好可以用 for 循环里的 i 来代替,在想 结果list 中添加 templist 的时候要判断一下大小即可
我一开始直接用 for 对为考虑这些条件的结果进行筛选,去掉大小不为 k 的集合,虽然也ac了,但是只beat 3%。。。
未优化:
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
int[] nums = {1,2,3,4,5,6,7,8,9};
List<List<Integer>> list = new ArrayList<>();
List<List<Integer>> solu = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums, n, 0);
for(int i = 0;i < list.size();i++){
if(list.get(i).size()==k){
solu.add(list.get(i));
}
}
return solu;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
if(remain < 0) return;
else if(remain == 0) list.add(new ArrayList<>(tempList));
else{
for(int i = start; i < 9; i++){
tempList.add(nums[i]);
backtrack(list, tempList, nums, remain - nums[i], i+1); // not i + 1 because we can reuse same elements
tempList.remove(tempList.size() - 1);
}
}
}
}//3ms
优化过的,AC:
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
combination(ans, new ArrayList<Integer>(), k, 1, n);
return ans;
}
private void combination(List<List<Integer>> ans, List<Integer> comb, int k, int start, int n) {
if (comb.size() == k && n == 0) {
List<Integer> li = new ArrayList<Integer>(comb);
ans.add(li);
return;
}
for (int i = start; i <= 9; i++) {
comb.add(i);
combination(ans, comb, k, i+1, n-i);
comb.remove(comb.size() - 1);
}
}
}//1ms