【Leetcode】Combination Sum III
2015-11-28 16:18
330 查看
题目链接:https://leetcode.com/problems/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.
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:
思路:
候选集没有重复元素,每个元素只选一次,跟上题不同的是,限制了搜索步数。因为没有重复解的问题,所以无需用HashSet,只需要加入对步数的判断就好了
算法:
题目:
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:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
思路:
候选集没有重复元素,每个元素只选一次,跟上题不同的是,限制了搜索步数。因为没有重复解的问题,所以无需用HashSet,只需要加入对步数的判断就好了
算法:
List<List<Integer>> iLists = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); int target = 0; int k = 0; public List<List<Integer>> combinationSum3(int k, int n) { this.target = n; this.k = k; dspCombination(0, 1); return iLists; } private void dspCombination(int sum, int level) { if (sum == target && list.size() == k) { //限制搜索步数 iLists.add(new ArrayList<Integer>(list)); return; } else if (list.size() > k) { return; } else if (sum > target) { return; } else { for (int i = level; i <= 9; i++) { sum += i; list.add(i); dspCombination(sum, i + 1);// list.remove(list.size() - 1); sum -= i; } } }
相关文章推荐
- 桶排序
- MYSQL---命令行方式导入sql文件
- C++拷贝构造函数
- centOS 更新python版本
- 【译】聚类分析
- 1-3-17:用边长求三角形面积
- Restore IP Addresses
- Zabbix 2.4.5 源码包安装及使用
- Bug 小记(**贵金属)
- 利用Dojo进行DOM事件编程
- CSS3 新增颜色表示方式
- 【64.22】【E】【leetcode】Pascal's Triangle II
- codeforces B.Queries about less or equal elements
- Android改变状态栏
- 我的第一篇博客 嘿嘿
- 最大公约数之和
- java -> sql 数据类型
- 用为知发布博客到博客园、使用Wiz编写和发布博客园(cnblogs)博客
- nyoj Change the ball 313 (技巧&思想)
- 设计模式(七)门面模式(Facade Pattern 外观模式)