leetcode 216. 组合总和 III c++ 2021-07-10

leetcode 216. 组合总和 III c++ 2021-07-10

class Solution {
public:
    
    vector<vector<int>> combinationSum3(int k, int n) 
    {
        backTracing(k, n, 0, 1);
        return result;
    }
private:
    vector<vector<int>> result;
    vector<int> path;
    void backTracing(int k, int n, int sum, int startIndex);
};

inline void Solution::backTracing(int k, int n, int sum, int startIndex)
{
    if (sum > n)//减少循环都是剪枝
    {
        return;
    }

    if (path.size() == k)
    {
        if (sum == n) result.push_back(path);
        return;
    }

    for (int i = startIndex; i <= (9 - (k - path.size()) + 1); ++i)
    {
        path.push_back(i);
        sum += i;
        backTracing(k, n, sum, i + 1);
        sum -= i;
        path.pop_back();
    }
}
上一篇:评估速达3000开发工作量


下一篇:使用nodejs连接mysql数据库实现增删改查