递归回溯实现


  • 0

    class Solution {
    public:
    vector<vector<int> > combinationSum3(int k, int n) {
    vector<vector<int> > v;
    vector<int> temp;
    combinationSum3(k, n, v, temp);
    return v;
    }
    void combinationSum3(int k, int n, vector<vector<int> > & v,
    vector<int>& temp) {
    if (k == 1) {
    int last = temp[temp.size() - 1];
    if (n > last && n <= 9) {
    temp.push_back(n);
    v.push_back(temp);
    temp.pop_back();
    }
    } else {
    int i = 1;
    if (temp.size() > 0) {
    i = temp[temp.size() - 1] + 1;
    }
    for (; (2 * i + k - 1) * k <= 2 * n && i <= 9; i++) {
    temp.push_back(i);
    combinationSum3(k - 1, n - i, v, temp);
    temp.pop_back();
    }
    }
    }
    };


Log in to reply
 

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