712210. Combination Sum II

Medium

Combination Sum II

Slug: combination-sum-ii

Difficulty: Medium

Id: 712210

Topic Tags: None

Company Tags: None

Summary

The Combination Sum II problem involves finding all possible combinations of a given array that sum up to a target value, without considering the order of elements. This problem requires a combination of recursion and dynamic programming to solve efficiently.

Detailed Explanation

To solve this problem, we can use a recursive approach with memoization to keep track of already computed combinations. The basic idea is to iterate through the input array, selecting each element as many times as it appears in the array (since duplicates are allowed), and recursively generate all possible combinations that sum up to the target value.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty list result to store the final combinations.
  2. Define a recursive function combinationSum2 that takes three parameters: nums, target, and start. start represents the starting index for the current recursion level.
  3. Iterate through the input array nums from the start index to its end.
  4. For each element at the current index, recursively call combinationSum2 with the updated start index (i.e., i + 1) and the remaining target value (target - nums[i]). This will generate all possible combinations that sum up to the reduced target value.
  5. If the recursive function returns a non-empty list of combinations, add it to the result list.
  6. Return the result list containing all possible combinations that sum up to the original target value.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class CombinationSumII {
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        combinationSum2Helper(result, new ArrayList<>(), nums, target, 0);
        return result;
    }

    private void combinationSum2Helper(List<List<Integer>> result, List<Integer> tempList, int[] nums, int remain, int start) {
        if (remain < 0) return;
        else if (remain == 0) result.add(new ArrayList<>(tempList));
        else for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) continue;
            if (nums[i] > remain) break;
            tempList.add(nums[i]);
            combinationSum2Helper(result, tempList, nums, remain - nums[i], i + 1);
            tempList.remove(tempList.size() - 1);
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.