216. Combination Sum III(unsolved)
来源:互联网 发布:软件开发流程管理规范 编辑:程序博客网 时间:2024/05/16 15:37
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.
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]]
思路:这道题其实没有很理解。
主要的方法是递归。其实就是对于从一开始的每个数,往后考虑,并且加限制条件。注意应该在path中压入现有的i后再往下找,然后pop出现有的i。其实就是结合栈和递归来查找。
其实运行顺序可能是这样的。
1 1 1
1 1 2
1 1 3
。。。
1 2 1
1 2 2
1 2 3
1 2 4
1 2 5
。。。
1 3 1
。。。
都是依次类推的。这是栈里数字的运行过程。
class Solution {public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> result; vector<int> path; backtrack(result,path, k,1,n); return result; } void backtrack(vector<vector<int>>& result,vector<int>& path,int k,int start,int target) {//递归时,结束条件一般放前面 if(target==0&&k==0) { result.push_back(path); return ; } for(int i=start;i<=target&&i<10;i++) { path.push_back(i); backtrack(result,path,k-1,i+1,target-i); path.pop_back(); } }};
0 0
- 216. Combination Sum III(unsolved)
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 409. Longest Palindrome
- 验证两个字段,如果为空显示错误
- Redis有多快?
- 欢迎使用CSDN-markdown编辑器
- ContentProvider 学习笔记(一)
- 216. Combination Sum III(unsolved)
- 使用tempest测试openstack
- UVA 10763
- 测试人员应该如何发展?
- opencv学习_11 (moravec角点检测及缺点)
- Oracle导入导出工具
- js内存泄漏的几种情况
- 米斯特白帽培训讲义(v2)漏洞篇 弱口令、爆破、遍历
- android改变状态栏背景为应用背景