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 }