LeetCode 216 Combination Sum III
2016-05-16 16:17
375 查看
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:
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]]
public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new LinkedList<List<Integer>>(); List<Integer> tmp = new ArrayList<Integer>(); dfs(1, k, n, tmp, result); return result; } private void dfs(int begin, int k, int rest, List<Integer> tmp, List<List<Integer>> result) { /**注意这个终止条件*/ if (rest == 0 && k == 0) /**tmp是变动的,所以此处需要new一个*/ result.add(new ArrayList<Integer>(tmp)); /*分别i开始往下深搜*/ for (int i = begin; i <= 9 && i <= rest; i++) { tmp.add(i); dfs(i + 1, k - 1, rest - i, tmp, result);//搜索下个数字 tmp.remove(tmp.size() - 1);//回溯 } }
相关文章推荐
- 利用Azure Automation实现云端自动化运维(2)
- jQuery功能强大的图片查看器插件
- 正则匹配:Email 密码强度 身份证 手机号 日期 数字每4个字空一格等
- linux mysql 双主复制配置文件my.cnf
- Svg.js实例教程及使用手册详解(一)
- Flask(3)-模版
- 值得推荐的算法学习网站
- 基于partition——最小的K个数、数组中出现次数超过一半的数字
- Android Selector和Shape的组合
- DeepID人脸识别算法之三代
- VB作业
- 利用Azure Automation实现云端自动化运维(4)
- 如何去阅读并学习一些优秀的开源框架的源码?
- PBOC借/贷记IC卡终端专用参数信息
- Swift开篇001->新建Swift工程
- Activiti生成流程图
- 作业
- PySide——Python图形化界面入门教程(二)
- thinkphp中定义自己的函数
- Java TreeMap工作原理及实现(二)