↻one more pass.
Backtracking · Medium

Combination Sum II: the idea to remember.

Find distinct combinations summing to a target when each input occurrence may be used once.

Solve on LeetCode ↗

The core insight

Sort candidates, skip duplicates at the same depth, and continue from the next index after a choice.

Why it works

Advancing the index enforces occurrence limits, while same depth skipping removes duplicate value combinations.

The mistake to avoid

Unlike Combination Sum, recurse with the next index so an occurrence is not reused.

Time: O(n · 2^n) conservative boundSpace: O(n) auxiliary plus output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Sort candidates, skip duplicates at the same depth, and continue from the next index after a choice.
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    Arrays.sort(candidates);
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    List<Integer> ls = new ArrayList<Integer>();
    comb(candidates, target, ans, ls, 0);
    return ans;
}

public void comb(
    int[] candidates,
    int target,
    List<List<Integer>> ans,
    List<Integer> ls,
    int index
) {
    if (target == 0) {
        ans.add(new ArrayList(ls));
    } else if (target < 0) return; else {
        for (int i = index; i < candidates.length; i++) {
            if (i > index && candidates[i] == candidates[i - 1]) continue;
            ls.add(candidates[i]);
            comb(candidates, target - candidates[i], ans, ls, i + 1);
            ls.remove(ls.get(ls.size() - 1));
        }
    }
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.