[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 -- 重点,dfs回溯模板

https://leetcode.com/problems/combination-sum-iii/简单。总结自己的回溯模板class Solution(object): def dfs(sel...
  • xyqzki
  • xyqzki
  • 2015年12月14日 14:25
  • 377

leetcode 216. Combination Sum III

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

LeetCode 216 Combination Sum III(Backtracking)(*)

翻译找出所有的k个数字相加得到数字n的组合,只有1到9的数字可以被使用,并且每个组合间需要是不同的数字集。原文Find all possible combinations of k numbers t...
  • NoMasp
  • NoMasp
  • 2016年07月17日 22:21
  • 1334

LeetCode 216. Combination Sum III 解题报告

LeetCode 216. Combination Sum III 解题报告

leetcode_middle_25_216. Combination Sum III

题意: 给两个数n,k,找出所有n个各不相同的数的和是k的组合。 分析: 其实关键就是搜索遍历,怎么遍历呢?可以这样: 1,2,3    1,2,4    1,2,5  ...   1,2...
  • pusude
  • pusude
  • 2017年02月07日 14:44
  • 82

LeetCode笔记:216. Combination Sum III

寻找k个数相加得到n的所有组合

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 Combination Sum III

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

LeetCode #216 - Combination Sum III - Medium

Combination Sum Series Combination Sum I: Combination Sum II: Combination Sum III: Pr...
  • Arcome
  • Arcome
  • 2016年12月20日 07:56
  • 346
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[leetcode][回溯] Combination Sum III
举报原因:
原因补充:

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