Share my c++ solution(0 ms)


  • 0
    L
    class Solution {
        private:
            vector<vector<int>> rest;
            vector<char>flag;
        public:
            void getNext(vector<int>&vec,int ind,int k,int n,int sum)
            {
                if(ind==k)
                {
                    if(sum==n)
                    {
                        rest.push_back(vec);
                        sort(rest.back().begin(),rest.back().end());
                    }
                    return;
                }
        		int s=ind==0?1:vec[ind-1]+1;
                for(int i=s;i<10;i++)
                {
                    if(!flag[i] && sum+i<=n)
                    {
                        flag[i]=1;
                        vec.push_back(i);
                        getNext(vec,ind+1,k,n,sum+i);
                        vec.pop_back();
                        flag[i]=0;
                    }
                }
                return;
            }
            vector<vector<int>> combinationSum3(int k, int n) {
                if(k<1 || n<1) return rest;
                //fill(flag.begin(),flag.end(),0);
        		for(int i=0;i<11;i++)
        			flag.push_back(0);
                vector<int>vec;
                getNext(vec,0,k,n,0);
                return rest;
            }
        };

Log in to reply
 

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