[LeetCode] 216. Combination Sum III

来源:互联网 发布:js中嵌套java代码 编辑:程序博客网 时间:2024/05/16 14:07

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
// 0msclass Solution {public:    vector<vector<int>> combinationSum3(int k, int target) {        vector<vector<int>> res;        vector<int> comb;        combinationSum3(res, comb, k, 9, target);        return res;    }private:    void combinationSum3(vector<vector<int>> &res, vector<int> &comb, int k, int n, int target) {        for ( ; n >= k; n--) {            if (n == target && k == 1) {                comb.push_back(n);                res.push_back(comb);                comb.pop_back();            } else if (n < target && k > 1) {                comb.push_back(n);                combinationSum3(res, comb, k - 1, n - 1, target - n);                comb.pop_back();            }        }    }};
原创粉丝点击