您的位置:首页 > 其它

[leetcode] 216. Combination Sum III 解题报告

2015-12-30 06:57 405 查看
题目链接:https://leetcode.com/problems/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.
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]]


思路:一个基本的DFS的题目。一个数可以拿,可以不拿,因此用DFS,将符合条件的答案都加入到结果中去。

代码如下:

class Solution {
public:
void DFS(int k, vector<int> vec, int sum, int cur, int n)
{
if(k==0 && sum == n) result.push_back(vec);
if(k <= 0 || sum > n || cur > 9) return;
DFS(k, vec, sum, cur+1, n);
vec.push_back(cur);
DFS(k-1, vec, sum+cur, cur+1, n);
}

vector<vector<int>> combinationSum3(int k, int n) {
vector<int> vec;
DFS(k, vec, 0, 1, n);
return result;
}
private:
vector<vector<int>> result;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: