LeetCode-39 組合總和
題目鏈接:https://leetcode-cn.com/problems/combination-sum/
給定一個無重複元素的數組
candidates
和一個目標數target
,找出candidates
中所有可以使數字和爲target
的組合。
candidates
中的數字可以無限制重複被選取。說明:
- 所有數字(包括
target
)都是正整數。- 解集不能包含重複的組合。
示例 1:
輸入: candidates = [2,3,6,7],target = 7, 所求解集爲: [ [7], [2,2,3] ]
示例 2:
輸入: candidates = [2,3,5],target = 8, 所求解集爲: [ [2,2,2,2], [2,3,3], [3,5] ]
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
combinationSum(candidates, target, 0, new ArrayList<>(), result);
return result;
}
// 回溯算法
// 1、題目爲無重複數組,故不需去重
// 2、數字可被無限重複選取,故從start本身開始遞歸
public static void combinationSum(int[] candidates, int target, int start, List<Integer> temp, List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<>(temp));
return;
}
if (target < 0) {
return;
}
for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
temp.add(candidates[i]);
combinationSum(candidates, target - candidates[i], i, temp, result);
temp.remove(temp.size()-1);
}
}
LeetCode-40 組合總和Ⅱ
題目鏈接:https://leetcode-cn.com/problems/combination-sum-ii/
給定一個數組
candidates
和一個目標數target
,找出candidates
中所有可以使數字和爲target
的組合。
candidates
中的每個數字在每個組合中只能使用一次。說明:
- 所有數字(包括目標數)都是正整數。
- 解集不能包含重複的組合。
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集爲: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
示例 2:
輸入: candidates = [2,5,2,1,2], target = 5, 所求解集爲: [ [1,2,2], [5] ]
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
combinationSum2(candidates, target, 0, new ArrayList<>(), result);
return result;
}
// 回溯算法
// 1、題目爲重複數組,故需要去重
// 2、數字只能選取一次,故從start+1開始遞歸
public static void combinationSum2(int[] candidates, int target, int start, List<Integer> temp, List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
if (i > start && candidates[i] == candidates[i-1]) // 去重
continue;
temp.add(candidates[i]);
combinationSum2(candidates, target - candidates[i], i+1, temp, result);
temp.remove(temp.size()-1);
}
}