LeetCode 40. Combination Sum II

原題連接在這裏:https://leetcode.com/problems/combination-sum-ii/html

題目:post

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.url

Each number in C may only be used once in the combination.spa

Note:code

  • 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: htm

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

題解:blog

Combination Sum很是類似 也是backtracking. 不一樣在於不能夠重複使用元素。其實只是遞歸時, start的參數更改成i+1便可.遞歸

Time Complexity: exponential.leetcode

Space: O(candidates.length). stack space.rem

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 }

跟上Combination Sum III.

相關文章
相關標籤/搜索