[leetcode][回溯] Combination Sum III

原创 2015年07月08日 15:16:10

题目:

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

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

Leetcode|Combination Sum III[回溯]

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

LeetCode Combination Sum III

Description: Find all possible combinations of k numbers that add up to a number n, given that ...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

《leetCode》:Combination Sum III

题目Find all possible combinations of k numbers that add up to a number n, given that only numbers fro...

[LeetCode - 回溯] 39. Combination Sum

1 问题 Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all u...

Combination Sum III C#

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

216 Combination Sum III [Leetcode]

题目内容: Find all possible combinations of k numbers that add up to a number n, given that only numbe...

Leetcode——216. Combination Sum III

题目:Find all possible combinations of k numbers that add up to a number n, given that only numbers fr...

leetcode 216. Combination Sum III

class Solution { void do_once(int k,int n, map, int>&candi) { map, int>newcandi; for (map, int...

leetCode(31):Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers fro...

[LeetCode]39.Combination Sum&40.Combination Sum II&216.Combination Sum III&377.Combination Sum IV

39.Combination Sum 40.Combination Sum II 216.Combination Sum III 377.Combination Sum IV
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)