C++ clean solution, back tracking, easy to understand


  • 0
    B
    class Solution {
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<vector<int>> res;
            vector<int> comb;
            helper(1, 0, k, n, comb, res);
    
            return res;
        }
    
        void helper(int startVal, int sum, int k, int n, vector<int>& comb, vector<vector<int>>& res) {
            if (comb.size() == k) {
                if (sum == n) {
                    res.push_back(comb);
                }
                return;
            }
    
            for (int i = startVal; i < 10; ++i) {
                comb.push_back(i);
                helper(i + 1, sum + i, k, n, comb, res);
                comb.pop_back();
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.