Leetcode: Combination Sum III
2015-12-17 12:56
148 查看
ind 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]]
Use recursion, or DFS
One syntax to notice is line 3:
List<List<Integer>> res = new ArrayList<List<Integer>>();
List is abstract and can not be instantiated
public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> item = new ArrayList<Integer>(); helper(res, item, k, n, 1); return res; } public void helper(List<List<Integer>> res, List<Integer> item, int num, int remain, int start) { if (remain < 0) return; if (num == 0) { if (remain == 0) { res.add(new ArrayList<Integer>(item)); } return; } for (int i=start; i<=9; i++) { item.add(i); helper(res, item, num-1, remain-i, i+1); item.remove(item.size()-1); } } }
相关文章推荐
- Java之多线程内存可见性_2(volatile实现可见性)
- 初始化配置CentOS7
- 删除ubuntu卸载后的bootloader
- 读书学习之道
- OC MRC之循环引用问题(代码分析)
- bat 运行java程序
- leetcode刷题日记——Valid Anagram
- 开荒第一篇!SHU1981 Handsome yaoge(用余数考虑倍数问题)
- postgresql分区表2
- DBA的技能图谱
- BZOJ3956: Count
- 直接双击启动tomcat中的startup.bat闪退原因及解决方法
- 第13周项目2 算法验证—Dijkstra算法
- 黑马程序员--Java编程之集合阶段总结
- quick 3.3 中绑定WebView
- PHP对数组的常用处理
- postgresql分区表1
- Hello world
- [数据存储之一]NSCoding协议练习
- UIAlertViewController详解