[Leetcode]Combination Sum III
2015-11-16 21:45
239 查看
LeetCode OJ
LeetCode Premium Subscription
Problems
Pick One!
Courses
Discuss
Book
WooStam
Combination Sum III My Submissions Question
Total Accepted: 17981 Total Submissions: 56703 Difficulty: Medium
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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
LeetCode Premium Subscription
Problems
Pick One!
Courses
Discuss
Book
WooStam
Combination Sum III My Submissions Question
Total Accepted: 17981 Total Submissions: 56703 Difficulty: Medium
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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int> > res; vector<int> tem; dfs(k,n,1,tem,res); return res; } private: void dfs(int k,int n,int i,vector<int>& tem,vector<vector<int> >& res){ if(k == 0 && n == 0){ res.push_back(tem); //tem.clear();//开始时候写了这句怎么改怎么错,原先想的是把这个tem放进结果之后,tem就要清空用来存下一个可能的序列.事实上,所谓的删除操作直接由下面的tem.pop_back()完成了。这里很值得我注意! return; } if(k == 0 && n > 0) return; for(int j = i;j <= 9;++j){ tem.push_back(j); dfs(k - 1,n - j,j + 1,tem,res); tem.pop_back(); } return; } };
相关文章推荐
- CSS-div高度100%设置问题
- 设计一款给爸爸妈妈用的手机
- oracle sql别名
- linux 安装与启动nginx
- 调整数组使奇数全部都位于偶数前面。
- 关于Collection接口的个人理解
- 巴黎事件发生后,Facebook、Twitter、Google和Uber都做了什么?
- 02_不声明第三个变量实现冒泡排序
- iOS平台基于KVC的JSON与数据对象绑定
- 完美软件不是结果,是追求
- Java程序员常用工具集
- Android-UI布局---RecyclerView学习(四)匹配GridLayoutManager的ItemDecoration
- 随意细解:UI -- 设计模式、手势识别
- QT 的信号与槽
- 菜鸟学习Cocos2d-x 3.x——内存管理
- jquery 使用方法(转载)
- LeetCode Sum Root to Leaf Numbers(DFS)
- Oracle数据的导入导出命令
- 随时笔记---修改ip访问外网
- [LeetCode]Next Permutation