40. 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 sum1的区别最大的就是会不会包含它本身。代码如下:

 1 public class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         Arrays.sort(candidates);
 5         backtracking(res,candidates,target,new ArrayList<Integer>(),0);
 6         return res;
 7     }
 8     public void backtracking(List<List<Integer>> res,int[] candidates,int target,List<Integer> list,int start){
 9         if(target==0){
10             res.add(new ArrayList<Integer>(list));
11         }else if(target<0) return;
12         else{
13             for(int i=start;i<candidates.length;i++){
14                 if(i>start&&candidates[i]==candidates[i-1]){
15                     continue;
16                 }
17                 list.add(candidates[i]);
18                 backtracking(res,candidates,target-candidates[i],list,i+1);
19                 list.remove(list.size()-1);
20             }
21         }
22     }
23 }

 

posted @ 2017-02-11 11:43  CodesKiller  阅读(120)  评论(0编辑  收藏  举报