[leetcode][回溯] Combination Sum III

来源:互联网 发布:许巍 完美生活 知乎 编辑:程序博客网 时间:2024/04/30 15: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.

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]]
class Solution {public:    vector<vector<int>> combinationSum3(int k, int n) {vector<vector<int> > res;if (k <= 0 || n <= 0) return res;vector<int> oneCombination;combinationSum3Core(k, n, 1, 0, oneCombination, res);return res;}private:    void combinationSum3Core(int k, int n, int start, int sum, vector<int> oneCombination, vector<vector<int> > &res){if (start > 9 || sum >= n || oneCombination.size() == k){if (oneCombination.size() == k && sum == n) res.push_back(oneCombination);return;}for (int i = start; i <= 9; ++i){oneCombination.push_back(i);combinationSum3Core(k, n, i + 1, sum + i, oneCombination, res);oneCombination.pop_back();}}};

leetcode测试运行时间不到1ms

0 0
原创粉丝点击