My C++ solutions


  • 0
    T
    class Solution {
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<vector<int>> sols;
            vector<int> path;
            getCombination(sols, path, n, k, 1);
            return sols;
        }
        void getCombination(vector<vector<int>>& sols, vector<int> path, int target, int k, int index) {
            if (target == 0 && path.size() == k) {
                sols.push_back(path);
                return;
            }
            else {
                for (int i = index; i <= 9 && i <= target && path.size() < k; i++) {
                        path.push_back(i);
                        getCombination(sols, path, target-i, k, i+1);
                        path.pop_back();
                }
            }
        }
    };

Log in to reply
 

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