40. Combination Sum II

来源:互联网 发布:php汽车管理系统 编辑:程序博客网 时间:2024/06/07 00:01

排序 + DFS


注意要去掉重复部分,

if(i != start && candidates[i] == candidates[i-1])continue;

注意不是

if(i != 0 && candidates[i] == candidates[i-1])continue;




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]]


import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution {List<List<Integer>> rst = new ArrayList<List<Integer>>();List<Integer> t = new ArrayList<Integer>();    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        Arrays.sort(candidates);        dfs(candidates, 0, target);        return rst;    }private void dfs(int[] candidates, int start, int target) {if(target == 0) {List<Integer> temp = new ArrayList<Integer>(t);rst.add(temp);return;}if(target < 0)return;for(int i=start; i<candidates.length; i++) {if(i != start && candidates[i] == candidates[i-1])continue;t.add(candidates[i]);dfs(candidates, i+1, target-candidates[i]);t.remove(t.size()-1);}}}


0 0