LeetCode – Combination Sum II (Java)

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.

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

Java Solution

This problem is an extension of Combination Sum. The difference is one number in the array can only be used ONCE.

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    List<Integer> curr = new ArrayList<Integer>();
    helper(result, curr, 0, target, candidates);
    return result;
public void helper(List<List<Integer>> result, List<Integer> curr, int start, int target, int[] candidates){
        result.add(new ArrayList<Integer>(curr));
    int prev=-1;
    for(int i=start; i<candidates.length; i++){
        if(prev!=candidates[i]){ // each time start from different element
            helper(result, curr, i+1, target-candidates[i], candidates); // and use next element only
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";