1.组合
If n = 4 and k = 2, a solution is:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
public List<List<Integer>> combine(int n, int k) {List<List<Integer>> combinations = new ArrayList<>();List<Integer> combineList = new ArrayList<>();backtracking(combineList, combinations, 1, k, n);return combinations;}private void backtracking(List<Integer> combineList, List<List<Integer>> combinations, int start, int k, final int n) {if (k == 0) {combinations.add(new ArrayList<>(combineList));return;}for (int i = start; i <= n - k + 1; i++) { // 剪枝combineList.add(i);backtracking(combineList, combinations, i + 1, k - 1, n);combineList.remove(combineList.size() - 1);}}
2.组合求和
given candidate set [2, 3, 6, 7] and target 7,A solution set is:[[7],[2, 2, 3]]
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
backtracking(new ArrayList<>(), combinations, 0, target, candidates);
return combinations;
}
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations,
int start, int target, final int[] candidates) {
if (target == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] <= target) {
tempCombination.add(candidates[i]);
backtracking(tempCombination, combinations, i, target - candidates[i], candidates);
tempCombination.remove(tempCombination.size() - 1);
}
}
}
3.组合综合 III
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
从 1-9 数字中选出 k 个数不重复的数,使得它们的和为 n。
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backtracking(k, n, 1, path, combinations);
return combinations;
}
private void backtracking(int k, int n, int start,
List<Integer> tempCombination, List<List<Integer>> combinations) {
if (k == 0 && n == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
if (k == 0 || n == 0) {
return;
}
for (int i = start; i <= 9; i++) {
tempCombination.add(i);
backtracking(k - 1, n - i, i + 1, tempCombination, combinations);
tempCombination.remove(tempCombination.size() - 1);
}
}
