[Leetcode 40]組合數和II Combination Sum II
阿新 • • 發佈:2018-12-01
posit none numbers ray 參考 tle p s size tar
【題目】
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
-
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
- All numbers (including
Example 1:
Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
【思路】
回溯,關鍵在去重:sort後nums[i-1]==nums[i] continue。
1、[Leetcode 78]求子集 Subset https://www.cnblogs.com/inku/p/9976049.html
2、[Leetcode 90]求含有重復數的子集 Subset II https://www.cnblogs.com/inku/p/9976099.html
3、講解在這: [Leetcode 216]求給定和的數集合 Combination Sum III
4、[Leetcode 39]組合數的和Combination Sum
【代碼】
有參考39的思路設置全局變量+兩種情況合並。
class Solution { private static List<List<Integer>> ans ; public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); ans = new ArrayList<>(); fun(new ArrayList<Integer>(),candidates,target,0); return ans; } public void fun(List<Integer> tmp,int[] data, int aim,int flag){ if(aim<=0){ if(aim==0){ ans.add(new ArrayList<>(tmp)); } return; } for(int i=flag;i<data.length;i++){ if(i>flag&&data[i-1]==data[i]) continue; tmp.add(data[i]); fun(tmp,data,aim-data[i],i+1); tmp.remove(tmp.size()-1); } } }
[Leetcode 40]組合數和II Combination Sum II