Whats wrong with my code?


  • 0
    J

    My solution is a classic recursive one. I recursively construct a vector and when its sum reaches n i push it to the answer vector. The problem is that the helper function can't go under the recursion, so with testcase like k=1, the answer is right; but when k>1, the helper function can only go into the first recursion. I added a cout sentence to debug(testcase 2,9), and it indicates that the helper function only work in first level.

      class Solution {
    

    private:
    vector<vector<int>> res;
    public:
    void helper(int k,int n,int sum, vector<int> a){
    if(k==0&&n==0) {

            res.push_back(a);
            return;
        }
    
        else{
            
            for(int i=1;i<=9&&sum+i<=n;i++ ){
                if(a.size()>0&&i<=a.back()) continue;
                if(k-1==0&&n-i!=0) continue;
                if(k-1!=0&&n-i==0) continue;
                a.push_back(i);
                //cout<<i<<endl;
                helper(k-1,n-i,sum+i,a);
                
            }
            
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int>a;
        helper(k,n,0,a);
        return res;
    }
    

    };


Log in to reply
 

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