[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:
Example 2:
Input: k = 3, n = 9
Output:
思路:一个基本的DFS的题目。一个数可以拿,可以不拿,因此用DFS,将符合条件的答案都加入到结果中去。
代码如下:
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; };
相关文章推荐
- Java2.2 多路分支switch-case
- 微软开源全新的文档生成工具DocFX
- 不小心修改了系统的文件, 引起的错误.
- 函数返回局部变量
- Lucene评分公式推到
- LeetCode - Plus One
- Java LinkedList - differences between retrieve operations
- 通过Lucene索引文件学习Lucene索引过程
- LeetCode - Valid Number
- *Factor Combinations
- 2015年总结
- 逆向编程
- LeetCode - Minimum Path Sum
- 其实很久以前就有写些技术博客的习惯了,不过都总是没有一个固定的保存地方……
- LeetCode - Unique Paths II
- BZOJ 2648 SJY摆棋子
- Leetcode: Additive Number
- protocol代理设计模式
- LeetCode - Unique Paths
- requirejs实验001.对我来说,用AMD的方式来组织代码并不轻松.