240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 14 | Leetcode 216. Combination Sum III

题解

Medium | Backtracking

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> sols;
        vector<int> sol;
        helper(n, k, 1, 0, sol, sols);
        return sols;
    }
    
    void helper(int n, int k, int index, int sum, vector<int>& sol, vector<vector<int>>& sols) {
        if(k == 0) {
            if(sum == n) sols.push_back(sol);
            return;
        }
        
        if(sum > n) return;
        
        for(int i = index; i <= 9; i++) {
            sol.push_back(i);
            sum += i;
            helper(n, k-1, i+1, sum, sol, sols);
            sum -= i;
            sol.pop_back();
        }
    }
};
posted @ 2020-09-29 12:15  CasperWin  阅读(83)  评论(0编辑  收藏  举报