LeetCode:組合總數II【40】
阿新 • • 發佈:2018-11-10
LeetCode:組合總數II【40】
題目描述
給定一個數組 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] ]
題目分析
這道題感覺全排列II來說還要簡單一些,整體還是遞歸回溯框架。
首先我們需要將陣列進行排序,這樣可以把相同元素放在一起,遞迴過程中保證同一個位置同一個值只使用一次。也就是如果已經在第1個位置上枚舉了“1”這個數字,那麼即使之後仍然有“1”的取值,也都跳過不進行列舉。
在實際的實現中,我們不妨這樣列舉,即將nums陣列排序後,只有nums[i]不等於nums[i-1]時,才將nums[i]視作一種可能的取值
for (int i = 0; i < nums.size(); i++) { // 確保在一個位置不會列舉兩個相同的數 if (i == nums.size() - 1 || nums[i] != nums[i -1]) { } }
或者說,我們是跳過當前元素,其實這樣的意思誰說,同一個取值的元素,我只取最左邊的一個。
if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates
Java題解
class Solution { public List<List<Integer>> combinationSum2(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); backtrack(list, new ArrayList<>(), nums, target, 0); return list; } private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){ if(remain < 0) return; else if(remain == 0) list.add(new ArrayList<>(tempList)); else{ for(int i = start; i < nums.length; i++){ if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates tempList.add(nums[i]); backtrack(list, tempList, nums, remain - nums[i], i + 1); tempList.remove(tempList.size() - 1); } } } }