# 【leetcode】组合总和

## 组合总和1

candidates 中的数字可以无限制重复被选取。

[
[7],
[2,2,3]
]

[
[2,2,2,2],
[2,3,3],
[3,5]
]

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, results, combine, 0);
return results;
}

private void backtrack(int[] candidates, int target, List<List<Integer>> results, List<Integer> combine, int begin) {
if (target == 0) {
return;
}

for (int i = begin; i < candidates.length; i++) {
if (target < candidates[i]) {
break;
}
backtrack(candidates, target - candidates[i], results, combine, i);
combine.remove(combine.size() - 1);
}
}
}


## 组合总和2

candidates 中的每个数字在每个组合中只能使用一次。

[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

[
[1,2,2],
[5]
]

class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, results, combine, 0);
return results;
}

private void backtrack(int[] candidates, int target, List<List<Integer>> results, List<Integer> combine, int start) {
if (target == 0) {
return;
}
for (int i = start; i < candidates.length; i++) {
if (target < candidates[i])
break;
if (i > start && candidates[i] == candidates[i - 1])
continue;
backtrack(candidates, target - candidates[i], results, combine, i + 1);
combine.remove(combine.size() - 1);
}
}
}


## 组合总和3

class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<Integer>(), n, k, 1);
return result;
}

private void backtrack(List<List<Integer>> result, List<Integer> combine, int target, int k, int start) {
if (target == 0 && combine.size() == k) {
return;
}

for (int i = start; i < 10 && i <= target; i++) {
backtrack(result, combine, target - i, k, i + 1);
combine.remove(combine.size() - 1);
}
}
}


07-03 566

07-03 285
12-18 309
08-06 115
02-02 41
07-03 279
09-09 117
12-19 100
04-28 301
03-17 46
09-12 1446
05-17 190
07-07 82
03-02 229
05-12 168
01-14 86