LeetCode 40. Combination Sum II
原题链接在这里:https://leetcode.com/problems/combination-sum-ii/
题目:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
题解:
与Combination Sum非常相似 也是backtracking. 不同在于不可以重复使用元素。其实只是递归时, start的参数更改为i+1即可.
Time Complexity: exponential.
Space: O(candidates.length). stack space.
AC Java:
1 class Solution { 2 public List<List<Integer>> combinationSum2(int[] candidates, int target) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(candidates == null || candidates.length == 0){ 5 return res; 6 } 7 8 Arrays.sort(candidates); 9 dfs(candidates, target, 0, new ArrayList<Integer>(), res); 10 return res; 11 } 12 13 private void dfs(int[] candidates, int target, int start, List<Integer> item, List<List<Integer>> res){ 14 if(target == 0){ 15 res.add(new ArrayList<Integer>(item)); 16 return; 17 } 18 19 if(target < 0){ 20 return; 21 } 22 23 for(int i = start; i<candidates.length; i++){ 24 if(i>start && candidates[i]==candidates[i-1]){ 25 continue; 26 } 27 28 item.add(candidates[i]); 29 dfs(candidates, target-candidates[i], i+1, item, res); 30 item.remove(item.size()-1); 31 } 32 } 33 }
AC Python:
1 class Solution: 2 def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 3 res = [] 4 candidates.sort() 5 self.dfs(candidates, target, 0, [], res) 6 return res 7 8 def dfs(self, candidates: List[int], target: int, start: int, item: List[int], res: List[List[int]]) -> None: 9 if target == 0: 10 res.append(item[:]) 11 return 12 13 for i in range(start, len(candidates)): 14 if candidates[i] > target: 15 continue 16 17 if i > start and candidates[i] == candidates[i - 1]: 18 continue 19 20 item.append(candidates[i]) 21 self.dfs(candidates, target - candidates[i], i + 1, item, res) 22 item.pop()