給定一個無重複元素的數組 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]
]
簡單解析:超級大暴力遞歸+剪枝
有兩點小優化:
- 排序
- 排序後就可以在
target - candidates[i] < 0
時直接return
,減少不必要的遞歸。
class Solution {
public void recursive(int [] candidates, int target, List<Integer> cur, List<List<Integer>> ans, int st) {
if (target == 0) {
ans.add(new ArrayList<>(cur));
return ;
}
for(int i = st; i < candidates.length; i++) {
if (target - candidates[i] >= 0) {
cur.add(candidates[i]);
recursive(candidates, target - candidates[i], cur, ans, i);
cur.remove(cur.size() - 1);
}else return ;
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
if (candidates.length == 0) return ans;
Arrays.sort(candidates);
recursive(candidates, target, cur, ans, 0);
return ans;
}
}
歡迎參觀我的個人博客:https://pyai.top