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]]
解法
回溯法,有序的,不包括本元素,并且判断条件增加temp.size() == num
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
int[] candidates = new int[9];
for (int i = 0; i < candidates.length; i++) {
candidates[i] = i + 1;
}
List<List<Integer>> ret = new ArrayList<>();
if (candidates == null || candidates.length == 0 || n <= 0) {
return ret;
}
Arrays.sort(candidates);
backtrack(ret, new ArrayList<Integer>(), candidates, n, k, 0);
return ret;
}
private void backtrack(List<List<Integer>> ret, List<Integer> temp, int[] candidates, int remain, int num, int start) {
if (remain == 0 && temp.size() == num) {
ret.add(new ArrayList<Integer>(temp));
} else if (remain < 0 || temp.size() > num) {
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] == candidates[i] - 1) continue;
temp.add(candidates[i]);
backtrack(ret, temp, candidates, remain - candidates[i], num, i + 1);
temp.remove(temp.size() - 1);
}
}
}
解法二
解法一的优化
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ret = new ArrayList<>();
backtrack(ret, new ArrayList<Integer>(), n, k, 1);
return ret;
}
private void backtrack(List<List<Integer>> ret, List<Integer> temp, int remain, int num, int start) {
if (remain == 0 && temp.size() == num) {
ret.add(new ArrayList<Integer>(temp));
} else if (remain < 0 || temp.size() > num) {
return;
}
for (int i = start; i <= 9; i++) {
temp.add(i);
backtrack(ret, temp, remain - i, num, i + 1);
temp.remove(temp.size() - 1);
}
}
}