leetcode刷題之旅(40)組合總和2
阿新 • • 發佈:2018-12-12
題目描述
給定一個數組 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] ]
思路分析
思路和上題一致,不過陣列中出現了重複元素,所以要加判斷條件,防止list中出現重複項
程式碼及結果
public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> list1 = new ArrayList<Integer>(); Arrays.sort(candidates); dfs(candidates, 0, target, list, list1); return list; } void dfs(int[] candidates, int start, int target, List<List<Integer>> list, List<Integer> list1){ if (target < 0) { return; } else if (target == 0) { list.add(new ArrayList<Integer>(list1)); } else { for (int i = start; i < candidates.length; i++) { if (i>start && candidates[i]==candidates[i-1]) { //判斷條件 continue; } list1.add(candidates[i]); dfs(candidates, i+1, target-candidates[i], list, list1); //改為i+1 避免元素多次使用 list1.remove(list1.size() - 1); } } }