Skip to main content

Combination Sum II | Leetcode : 40 | Medium | Using Recursion and Backtracking | Easy to Solve

If you are diving into the world of coding challenges, you might have encountered the "Combination Sum II" problem on LeetCode. This problem is not just about finding combinations but ensuring they are unique. In this blog post, we will explore how to solve this problem effectively, dissect the solution, and understand its time and space complexity in a better Way.

Problem Overview

The Combination Sum II problem asks you to find all unique combinations in a list of numbers that sum up to a specific target. Each number in the list can only be used once, and the solution must avoid duplicate combinations.

Example 1:

  • Input: candidates = [10,1,2,7,6,1,5], target = 8
  • Output:
    [
    [1,1,6], [1,2,5], [1,7], [2,6] ]

Example 2:

  • Input: candidates = [2,5,2,1,2], target = 5
  • Output:
    [ [1,2,2], [5] ]

C++ Code :-


    class Solution {
    public:

        void solve(vector<int>& candidates, int target, vector<int> v,
                    vector<vector<int>> &ans, int index) {
            if (target == 0) {
                ans.push_back(v);
                return;
            }

            if (target < 0)
                return;

            for (int i = index; i < candidates.size(); i++) {
                // Skip duplicates
                if (i > index && candidates[i] == candidates[i - 1])
                    continue;

                // Include the current number and explore further
                v.push_back(candidates[i]);
                solve(candidates, target - candidates[i], v, ans, i + 1);
               
                // Backtrack to explore other possibilities
                v.pop_back();
            }
        }

        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());  // Sort the candidates
            vector<int> v;  // Current combination
            vector<vector<int>> ans;  // To store all valid combinations

            solve(candidates, target, v, ans, 0);  // Start backtracking
            return ans;
        }
    };
   

How It Works

  1. Sorting the Candidates:

    • The candidates vector is sorted initially with sort(candidates.begin(), candidates.end()). This sorting helps in easily skipping duplicates later on.
  2. Recursive Backtracking Function (solve):

    • Base Case: When target is 0, it means the current combination v adds up to the desired target. Hence, v is added to ans.
    • Early Termination: If target becomes negative, it means the current path is invalid, so the function returns early.
    • Iterating and Skipping Duplicates: The loop starts from index to avoid recombination and skips over duplicates using if (i > index && candidates[i] == candidates[i - 1]) continue;.
    • Exploring New Combinations: The current number is added to the combination (v.push_back(candidates[i])), and the function recursively explores further possibilities by calling solve with the updated target and index.
    • Backtracking: After exploring the current path, the last added number is removed (v.pop_back()) to backtrack and explore other combinations.
  3. Main Function (combinationSum2):

    • Initializes the combination vector v and the result vector 'ans'.
    • Calls "solve" with the initial parameters to start the backtracking process.
    • Returns the 'ans' vector containing all unique combinations that sum up to the target.

Time and Space Complexity

Time Complexity:

  • The time complexity of this algorithm is O(2N)O(2^N), where NN is the number of candidates. This is because, in the worst case, the algorithm explores all possible subsets of the input list. Although the exact number of calls depends on the specific input, it’s exponential in the number of candidates.

Space Complexity:

  • The space complexity is O(N)O(N) for storing the current combination v and the recursive call stack. In the worst case, the depth of the recursion tree can go up to NN (the length of the candidates array), and the space required to store the current combination can also be O(N)O(N).

This solution effectively handles the "Combination Sum II" problem by utilizing sorting and backtracking to ensure all unique combinations are found without duplication. The approach is optimal for the problem constraints and efficiently manages the search space through careful pruning and duplication handling.

Keywords: Combination Sum II, C++ solution, coding interview, backtracking algorithm, unique combinations, time complexity, space complexity, Leetcode 40 solution, Leetcode 40 cpp solution, Leetcode 40 c++ solution, Leetcode 40 detailed solution, Leetcode Daily Practice, Leetcode Contest Solution

Popular posts from this blog

BCA 5th and 6th Semester Project | BCSP-064 | Synopsys and Project | Both | IGNOU BCA | 100% Accepted | July 2023 and Jan 2024

 Synopsys and Project | Both | July 2023 and Jan 2024 Title of the Project : - PRODUCT HUB Buy it from here (Synopsis + Project) : Synopsis Content :- Synopsis : An overview of the entire project, summarizing its main objectives, scope, and outcomes. Introduction : Introduce the project and provide context for the reader by explaining the problem or need that the project aims to address. Aim and Objective : Clearly state the goals and objectives of the project, outlining what you intend to achieve through its completion. Project Category : Define the domain or category to which the project belongs, helping readers understand the context and purpose of the project. Tools and Platform : List the software tools, programming languages, and platforms you'll be using to develop and implement the project. System Analysis : Discuss the preliminary analysis phase of the project, where you identify requirements,

Flowchart and Pseudocode to Find the Area of a Square

  Write a flowchart and pseudocode to find the area of a square. Pseudocode :-  1. Start 2. Input length of the square 3. Calculate area of square as length * length 4. Print area 5. End #C++Programming Language #codeDelhi

MCS-021 | Data and File Structures | IGNOU BCA Solved Assignment | July 2021 & January 2022

  Course Code :- MCS-021 Course Title :- Data and File Structures Assignment Number :- BCA(3)/021/Assignment/2021-22 Maximum Marks :-  100 Weightage :-   25% Last Dates for Submission :- 31st October, 2021 (For July Session) &  15th April, 2022 (For January Session)  This assignment has four questions which carry 80 marks. Answer all the questions. Each question carries 20 marks. You may use illustrations and diagrams to enhance the explanations. Please go through the guidelines regarding assignments given in the Programme Guide. All the implementations should be in C programming language. Question 1: Write an algorithm that accepts a Binary Tree as inputs and outputs the traversals of Inorder , Postorder and Preorder of it. Question 2: Is it possible to implement multiple queues in a Stack. Justify your answer.  Question 3: List the names of all Sorting Algorithms along with their Complexities (Best case, Average case and Worst case). List as many names as possible along