Share my simple C++ code


  • 0
    L
    class Solution {
    public:
        void dfs(int n,int k,int pos, vector<vector<int>> &res,vector<int> &path,int sum) {
            for(int i=pos+1; i<=9; i++) {
                if(9-i+1+path.size() < k) continue;
                path.push_back(i);
                if(sum+i == n && path.size()==k) {
                    res.push_back(path);
                    path.pop_back();
                    return;
                }
                dfs(n,k,i,res,path,sum+i);
                path.pop_back();
            }
        }
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<int> path;
            vector<vector<int>> res;
            dfs(n,k,0,res,path,0);
            return res;
        }
    };

Log in to reply
 

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