Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

216. Combination Sum III 🌟🌟

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

Backtracking Solution

Code

class Solution {
    void helper(int k, int n, vector<vector<int>>& ans, vector<int>& temp, int start)
    {
        // if n is 0 and we found the combination of size k
        if (n == 0 && temp.size() == k) {
            ans.push_back(temp);
            return;
        }

        // if n is less than 0 or we found the combination of size greater than k
        if (n <= 0 || temp.size() >= k) {
            return;
        }

        // try all possible numbers from start to 9
        for (int i = start; i <= 9; i++) {
            temp.push_back(i);
            helper(k, n - i, ans, temp, i + 1);
            temp.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum3(int k, int n)
    {
        vector<vector<int>> ans;
        vector<int> temp;
        helper(k, n, ans, temp, 1);
        return ans;
    }
};
``