Combination Sum III

题目来源
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]]

这道题的想法,就是直接递归回溯实现。

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> res;
        if (n > 45)
            return res;
        vector<int> item;
        cal(res, item, k, n, 1);
        return res;
    }
    
    void cal(vector<vector<int>> &res, vector<int> &item, int k, int n, int i)
    {
        if (k == 0 && n == 0) {
            res.push_back(item);
            return;
        }
        if (i > 9)
            return;
        item.push_back(i);
        cal(res, item, k-1, n-i, i+1);
        item.pop_back();
        cal(res, item, k, n, i+1);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容