1. 程式人生 > >Leetcode 216. Combination Sum III

Leetcode 216. Combination Sum III

文章作者:Tyan
部落格:noahsnail.com  |  CSDN  |  簡書

1. Description

Combination Sum III

2. Solution

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> combination;
        combinationSum3(result, combination, n, k, 1);
        return result;
    }


private:
    void combinationSum3(vector<vector<int>>& result, vector<int>& combination, int n, int& k, int begin) {
        const int END = 10;
        if(n < 0 || combination.size() > k) {
            return;
        }
        if(n == 0 && combination.size() == k) {
            result.push_back(combination);
            return;
        }
        for(int i = begin; i < END; i++) {
            combination.push_back(i);
            combinationSum3(result, combination, n - i, k, i + 1);
            combination.pop_back();
        }
    }
};

Reference

  1. https://leetcode.com/problems/combination-sum-iii/description/