-
题目:216. 组合总和 III
找出所有相加之和为 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]] -
思路
// 216. 组合总和 III
public class CombinationSum3 {
public static void main(String[] args) {
CombinationSum3 obj=new CombinationSum3();
obj.combinationSum3(3,7);
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
int[] candidates = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
Arrays.sort(candidates);
backTrack(candidates, result, new ArrayList<Integer>(), n, k, 0);
return result;
}
private void backTrack(int[] candidates, List<List<Integer>> result, ArrayList<Integer> list, int remain, int count, int start) {
if (remain < 0) {
return;
} else if (remain == 0 && count == 0) {
result.add(new ArrayList<>(list));
} else if (count==0) {
return;
} else {
for (int i = start; i < candidates.length; i++) {
list.add(candidates[i]);
//注意这里必须是count-1,而不能是count--或者--count,不然循环下一次方法的时候,count依然是3
backTrack(candidates, result, list, remain - candidates[i], count-1, i + 1);
list.remove(list.size() - 1);
}
}
}
}