Wednesday, March 15, 2017

[LintCode] 153 Combination Sum II 解题报告

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

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.


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


思路
要求所有的解,我们用DFS。
先排个序,然后开始找。需要去重。



Code
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>> res = new ArrayList<>();
        if (num == null || num.length == 0) {
            return res;
        }
        
        Arrays.sort(num);
        List<Integer> list = new ArrayList<>();
        helper(num, res, list, target, 0);
        return res;
    }
    
    public void helper(int[] num, 
                       List<List<Integer>> res, 
                       List<Integer> list, 
                       int target, 
                       int startIndex) {
        
        if (target == 0) {
            res.add(new ArrayList<Integer>(list));
            return;
        }
        
        for (int i = startIndex; i < num.length; i++) {
            if (i != startIndex && num[i] == num[i - 1]) {
                continue;
            }
            if (target < num[i]) {
                break;
            }
            list.add(num[i]);
            helper(num, res, list, target - num[i], i + 1);
            list.remove(list.size() - 1);
        }
    }
}