Combination Sum III 题解
2016-02-10 13:57
471 查看
题目:
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]]
Difficulty: Medium
翻译&分析:
Combination Sum第三道,给定一个数列,要求找出所有的子集,使每个子集有k个元素,子集元素之和为n,照比前两道稍有难度增加,实际上换汤不换药,具体分析详见:Combination Sum题解代码:
class Solution { vector<vector<int>> ret; vector<int> curr; public: void search(int k, int n, int i) { if (n == 0 && k == 0) { ret.push_back(curr); return; } if (k < 0 || n < 0 || i > 9) return; if ((k == 0 && n != 0) || (n == 0 && k != 0)) return; curr.push_back(i); search(k - 1, n - i, i + 1); curr.pop_back(); search(k, n, i + 1); } vector<vector<int>> combinationSum3(int k, int n) { if (k <= 0 || n <= 0 || k >= n) return ret; search(k, n, 1); return ret; } };
相关文章推荐
- 51nod 1215:数组的宽度 单调栈
- sql查询优化
- IoRegisterFsRegistrationChange routine
- 如何创建一个完整的C语言程序心得
- C/C++,笔试面试,多种方法求100以内的所有素数
- PHP---APP笔记
- 百岁老人(有照片)
- HDU——2056Rectangles(几何计算)
- 2016蓝桥杯算法训练——未名湖边的烦恼
- DP项目开发随记6-僵直
- Light OJ 1079 Just another Robbery (概率+背包)
- 1023. 组个最小数 (20)
- 设置MyEclipse中代码的换行长度
- cocos2d-x3.3 PageView常用成员函数
- Java认证考试实例疑难辨析(4)
- 顺序表应用3:元素位置互换之移位算法
- 在SWING里嵌入SWT的组件
- 326. Power of Three LeetCode
- 2016蓝桥杯算法训练——数字三角形
- 202. Happy Number LeetCode