leetcode-216. Combination Sum III
来源:互联网 发布:人力资源 知乎 编辑:程序博客网 时间:2024/06/06 06:40
216. Combination Sum III
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]]
题解:
推荐先看一下:
Combination Sum
Combination Sum II
和前面几题不同的就是这次对于集合是固定的,是 [1,2,3,4,5,6,7,8,9] ,要求的和为 n 的集合的大小必须为 k
所以对于固定的集合,正好可以用 for 循环里的 i 来代替,在想 结果list 中添加 templist 的时候要判断一下大小即可
我一开始直接用 for 对为考虑这些条件的结果进行筛选,去掉大小不为 k 的集合,虽然也ac了,但是只beat 3%。。。
未优化:
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { int[] nums = {1,2,3,4,5,6,7,8,9}; List<List<Integer>> list = new ArrayList<>(); List<List<Integer>> solu = new ArrayList<>(); backtrack(list, new ArrayList<>(), nums, n, 0); for(int i = 0;i < list.size();i++){ if(list.get(i).size()==k){ solu.add(list.get(i)); } } return solu; } private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){ if(remain < 0) return; else if(remain == 0) list.add(new ArrayList<>(tempList)); else{ for(int i = start; i < 9; i++){ tempList.add(nums[i]); backtrack(list, tempList, nums, remain - nums[i], i+1); // not i + 1 because we can reuse same elements tempList.remove(tempList.size() - 1); } } } }//3ms
优化过的,AC:
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> ans = new ArrayList<>(); combination(ans, new ArrayList<Integer>(), k, 1, n); return ans; } private void combination(List<List<Integer>> ans, List<Integer> comb, int k, int start, int n) { if (comb.size() == k && n == 0) { List<Integer> li = new ArrayList<Integer>(comb); ans.add(li); return; } for (int i = start; i <= 9; i++) { comb.add(i); combination(ans, comb, k, i+1, n-i); comb.remove(comb.size() - 1); } }}//1ms
阅读全文
0 0
- [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
- [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
- LeetCode 216. Combination Sum III
- java -- StringBuffer、Arrays系统方法用法
- 第3条:用私有构造器或者枚举类型强化Singleton属性
- 【工具】这是一篇获取工具的帖子
- 第十四周项目1
- Mac下关于pygame安装的问题
- leetcode-216. Combination Sum III
- python matplotlib中显示中文问题
- 冒泡排序-c++代码实现
- 欢迎使用CSDN-markdown编辑器
- C/C++windows多线程
- Spring之条件注解@Conditional,条件(系统)不同注入的对象也不同。
- 磁盘文件系统
- 根据 geoJson, 使用 d3 画出地图及经纬度打点
- [转]理解LSTM网络