Combination Sum II, Leetcode 解题笔记

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

只是上一道题的改动,注意candidate number里面有可能会出现重复的数字,要排除这种duplicate的情况。

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        Arrays.sort(candidates);
        search(ret, sol, candidates, target, 0, 0);
        return ret;
    }
    public void search(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int[] candidates, int target, int start, int sum){
        if(sum == target){
            ret.add(new ArrayList<Integer>(sol));
        }
        if(sum > target){
            return;
        }
        else{
            int last = -1;
            while(start < candidates.length && sum+candidates[start] <= target){
                if(candidates[start] != last){
                    sol.add(candidates[start]);
                    search(ret, sol, candidates, target, start+1, sum+candidates[start]);
                    last = candidates[start];
                    sol.remove(sol.size()-1);
                }
                start++;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s