LeetCode 之 Combination Sum III
2016-03-14 22:12
399 查看
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:
这道题和之前的全排列问题有点类似,先在1到9中选择一个元素i,把问题转化为(k-1,n-i)问题,这样递归解决,关键是我们要存储中间结果方便回溯,每次到达底部后(n==0和k==0)返回。代码如下:
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]]
这道题和之前的全排列问题有点类似,先在1到9中选择一个元素i,把问题转化为(k-1,n-i)问题,这样递归解决,关键是我们要存储中间结果方便回溯,每次到达底部后(n==0和k==0)返回。代码如下:
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> res; vector<int> ans; int i=1; combinationSum3(res,ans,i,k,n); return res; } void combinationSum3(vector<vector<int>>& res,vector<int>& ans,int low,int k,int n){ if(n==0&&k==0){ res.push_back(ans); return; }else if(n>0&&k>0){ for(int i=low;i<=n&&i<=9;i++){ ans.push_back(i); combinationSum3(res,ans,i+1,k-1,n-i); ans.pop_back(); } } } };
相关文章推荐
- 无边无状态栏窗口(使用GetWindowLongPtr设置GWL_EXSTYLE)
- Windows上安装Jekyll
- Dynamics CRM2016 Web API之通过实体的primary key查询记录
- LINUX和WINDOWS之间的文件共享
- 正定矩阵(positive definite matrix)
- Dynamics CRM2016 Web API之通过实体的primary key查询记录
- Dynamics CRM2016 Web API之通过实体的primary key查询记录
- Dynamics CRM2016 Web API之通过实体的primary key查询记录
- AlphaGo比Windows和Apple有更远更持久的影响力
- 手动绑定数据到GridView并实现编辑,删除,取消···
- Android 控件的触摸事件传递与处理
- visual c++ 中的stdafx.h头文件的作用
- HDU 5291 Candy Distribution DP 差分 前缀和优化
- Longest Substring Without Repeating Characters
- MySQL的高级查询
- Longest Substring Without Repeating Characters
- 解决使用tomcat6-maven-plugin时的"can not invoke tomcat manager"问题
- maven+eclipse基础
- C++ 多线程并发控制——互斥锁 pthread_mutex
- 二分查找算法----递归&&非递归