LeetCode 216. Combination Sum III (组合的和之三)
2017-09-07 05:19
351 查看
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]]
题目标签:Array, Backtracking
题目给了我们 k 和 n, 让我们找到 从1到9里的 k 个数字组合,没有重复,加起来之和等于 n。这道题目与前面两个版本的基本思路一样,利用 backtracking来做,就是有一些条件不一样而已。这题规定了只能从1 到 9 里选数字,之前两个版本的题目都是给的array;还有就是 这一题 规定了我们 数字的数量要等于 k。所以只要做一些条件的修改就可以了,具体看code。
Java Solution:
Runtime beats 45.85%
完成日期:09/06/2017
关键词:Array,Backtracking
关键点:加入数字 -> 递归 -> 去除最后一个数字 来测试所有的组合可能性
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> list = new ArrayList<>(); int len = 10; // use only numbers from 1 to 9 backtrack(list, new ArrayList<>(), n, 1, len, k); return list; } public boolean backtrack(List<List<Integer>> list, List<Integer> tempList, int remain, int start, int len, int size) { if(remain < 0 || tempList.size() > size) // if remain less than 0 or number limit exceeds return false; // no need to continue else if(remain == 0 && tempList.size() == size) // only add tempList into list { // when remain = 0 and number limit size matches list.add(new ArrayList<>(tempList)); return false; } else { for(int i=start; i<len; i++) { boolean flag; tempList.add(i); flag = backtrack(list, tempList, remain - i, i+1, len, size); // i + 1 because we cannot use same number more than once tempList.remove(tempList.size() - 1); if(!flag) // if find a tempList answer or fail, no need to continue that loop break; // because 1~9 is sorted and unique, the rest numbers are greater, they'll fail } return true; } } }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
相关文章推荐
- 数据结构与算法[LeetCode]—找出N个节点的BST的所有形态组合
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- leetCode 40.Combination Sum II(组合总和II) 解题思路和方法
- LeetCode 30. Substring with Concatenation of All Words(词语拼接组合)
- LeetCode 39. Combination Sum(给定和,求组合Ⅰ)
- 数据结构与算法[LeetCode]—Combinations 求1至n中所有K位数的所有组合
- LeetCode之组合数
- LeetCode 77. Combinations(组合)
- leetcode解题之 Combination Sum java 版(组合求和)
- leetcode_[python/C++] 17.Letter Combinations of a Phone Number(手机号码字符组合)
- (Java) LeetCode 39. Combination Sum —— 组合总和
- 【leetcode】31. Next Permutation 数字序列的所有组合中比给定串大的下一个最小的串
- Leetcode #49. Group Anagrams 变位词组合 解题报告
- LeetCode-----22. Generate Parentheses(n个()可能的组合)
- leetcode 括号组合题目 20 是否是有效括号 32 最大有效括号 301 去掉无效括号
- [leetcode 216] Combination Sum III ------组合数的和(回溯法)
- [LeetCode]-Generate Parentheses N个括号所有的组合数
- Leetcode22.+Leetcode216. 回溯法之应用(二):圆括号+组合问题
- Leetcode 78&90. Subsets I & II 【排列与组合的生成总结】
- 【LeetCode】Permutations && Combinations 排列组合