0ms C++ simple and clear solution with recursion


  • 2
    Q
    class Solution {
        vector<vector<int>> result;
        // the method is to get the combination
        // r is the start number to try which must be less than 10
        // v stores the numbers that have been tried
        void getCom(int k, int n, int r, vector<int>& v) {
            if (k == 0) {
                if (n == 0) result.push_back(v);
                return;
            }
            for (int i = r; i <= 9; ++i) {
                v.push_back(i);
                getCom(k - 1, n - i, i + 1, v);
                v.pop_back();
            }
        }
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<int> v;
            getCom(k, n, 1, v);
            return result;
        }
    };
    

Log in to reply
 

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