lintcode-medium-Combination Sum II

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

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

 

 Notice
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

Given candidate set [10,1,6,7,2,1,5] and target 8,

A solution set is:

[
  [1,7],
  [1,2,5],
  [2,6],
  [1,1,6]
]
public class Solution {
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // write your code here
        
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if(num == null || num.length == 0)
            return result;
        
        List<Integer> line = new ArrayList<Integer>();
        boolean[] visited = new boolean[num.length];
        Arrays.sort(num);
        
        helper(result, line, num, target, visited, 0);
        
        return result;
    }
    
    public void helper(List<List<Integer>> result, List<Integer> line, int[] num, int target, boolean[] visited, int start){
        
        if(target < 0)
            return;
        
        if(target == 0){
            result.add(new ArrayList<Integer>(line));
            return;
        }
        
        for(int i = start; i < num.length; i++){
            if(i > 0 && num[i] == num[i - 1] && !visited[i - 1])
                continue;
            
            line.add(num[i]);
            visited[i] = true;
            helper(result, line, num, target - num[i], visited, i + 1);
            line.remove(line.size() - 1);
            visited[i] = false;
        }
        
        return;
    }
    
}

 

posted @ 2016-03-16 06:41  哥布林工程师  阅读(177)  评论(0编辑  收藏  举报