[Leetcode] 216. Combination Sum III 解题报告
来源:互联网 发布:arcgis api for js 编辑:程序博客网 时间:2024/06/05 05:01
题目:
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]]
思路:
这是一道典型的Backtracking的题目,其实大家有没有发现它在实现上就是DFS?另外,由于要求出所有符合条件的解,所以我们会用到Backtracking的技术。思路就是:一旦发现符合题目要求的解,就把它添加到结果集合中。否则我们就让i从start + 1循环到9,尝试把i放在解中,并进行深度搜索。当然在循环的内部别忘了回溯(否则找不到所有的解)^_^。建议读者对这类题目设计一个实现模板。
代码:
class Solution {public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> results; vector<int> line; combinationSum3(results, line, k, n, 0, 0); return results; }private: void combinationSum3(vector<vector<int>>& results, vector<int> &line, int k, int n, int start, int sum) { if (sum >= n || line.size() >= k) { if (sum == n && line.size() == k) { results.push_back(line); } return; } for (int i = start + 1; i <= 9; ++i) { line.push_back(i); // try to add the i combinationSum3(results, line, k, n, i, sum + i); line.pop_back(); } }};
阅读全文
0 0
- [leetcode] 216. Combination Sum III 解题报告
- LeetCode 216. Combination Sum III 解题报告
- [Leetcode] 216. Combination Sum III 解题报告
- LeetCode-Combination Sum III-解题报告
- 【LeetCode】216.Combination Sum III(Medium)解题报告
- Combination Sum III解题报告
- leetcode Combination Sum解题报告
- LeetCode解题报告--Combination Sum
- [leetcode] 216.Combination Sum III
- LeetCode 216. Combination Sum III
- 216. Combination Sum III LeetCode
- [leetcode] 216. Combination Sum III
- [LeetCode]216. Combination Sum III
- leetcode 216. Combination Sum III
- LeetCode *** 216. Combination Sum III
- LeetCode 216. Combination Sum III
- leetcode.216. Combination Sum III
- leetcode 216. Combination Sum III
- android端上传后台数据 string字符串拼接问题
- leetcode No236. Lowest Common Ancestor of a Binary Tree
- Vue2+VueRouter2+webpack 构建项目实战(三)配置路由,整俩页面先
- MySQL server version for the right syntax to use near ';) T' at line 7
- Leetcode 338. Counting Bits
- [Leetcode] 216. Combination Sum III 解题报告
- UVa442
- JDBC
- ASM AMDU工具使用
- 半路出家, 我的iOS自学之路-2-头文件, 属性, 引用计数, 协议, 类别, 类扩展
- async异步问题(waterfall、parallel、eachSeries、map、whilst)
- cglib动态代理实现
- Contest_5 0614 By lhq
- gulp-删除文件和文件夹