Combination Sum II - Leetcode

public class Solution {
    public List> combinationSum2(int[] num, int target) {
        List> result = new ArrayList<>();
        List path  = new ArrayList<>();
        Arrays.sort(num);
        DFS(result, path, num, target, 0);
        return result;
    }
    private void DFS(List> result, List path, int[] pool, int gap, int start){
        if(gap == 0){
            ArrayList l = new ArrayList<>(path);
            if(!result.contains(l))
                result.add(l);
            return;
        }
        for(int i=start; i


2)

public class Solution {
    public List> combinationSum2(int[] num, int target) {
        List> result = new ArrayList<>();
        List path  = new ArrayList<>();
        Arrays.sort(num);
        DFS(result, path, num, target, 0);
        return result;
    }
    private void DFS(List> result, List path, int[] pool, int gap, int start){
        if(gap == 0){
            ArrayList l = new ArrayList<>(path);
           // if(!result.contains(l))
                result.add(l);
            return;
        }
        int previous = -1;
        for(int i=start; iif(previous == pool[i])
               continue;
               
            previous = pool[i];   
            
            path.add(pool[i]);
            DFS(result,path,pool,gap-pool[i],i+1);
            path.remove(path.size()-1);
        }
    }
}


分析:求所有可能的结果集。 第一种解法思路跟之前一样,唯一不同的是,1)每次从下一个元素开始遍历 2)对于结果集验证是否有重复的

第二个解法,效率提高很多,这里用到一个变量记录之前的值

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.

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

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 


你可能感兴趣的:(Leetcode)