[leetcode] 216. Combination Sum III

来源:互联网 发布:国内旅游数据 编辑:程序博客网 时间:2024/05/21 07:53

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.

Ensure that numbers within the set are sorted in ascending order.


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]]

这道题和第39题(传送门)、第40题(传送门)相关,大家可以先看下这两题。题目难度为Medium。

这道题限定了组合中的数字个数,整体思路和另外两题是相同的,不过这里不用去重了,难度应该比另外两题低些,在递归函数中注意判断数字个数就可以了。具体代码:

class Solution {    void getSum(vector<vector<int>>& rst, vector<int>& curRst, int cnt, int sum, int k, int n, int idx) {        if(cnt > k) return;        else if(cnt == k) {            if(sum == n) rst.push_back(curRst);        }        else {            for(int i=idx; i<=9; ++i) {                if(sum + i > n) return;                curRst.push_back(i);                getSum(rst, curRst, cnt+1, sum+i, k, n, i+1);                curRst.pop_back();            }        }    }public:    vector<vector<int>> combinationSum3(int k, int n) {        vector<vector<int>> rst;        vector<int> curRst;                getSum(rst, curRst, 0, 0, k, n, 1);                return rst;    }};

0 0
原创粉丝点击