Leetcode 39. Combination Sum
来源:互联网 发布:好用的护手霜 知乎 编辑:程序博客网 时间:2024/05/09 09:01
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[ [7], [2, 2, 3]]
首先排序是必须的,这没什么好说的
1.想到递归,每一层筛选出一个合理的数,并获得新的target值
2.每一层都要维护一个属于自己的list,传递给下一层的时候创建新的list进行传递(非常重要,每层维护的list容易混淆)
3.后一层都要从前一层选中的数的标号开始往后查找,并且要跳过前后两个数相同的坐标,这样避免出现重复
ps:貌似可以使用深度搜索做.目测效率不高,没有尝试
java代码如下
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> lists = new ArrayList<List<Integer>>(); combineSum(candidates, 0, target, lists, null); return lists; } public void combineSum(int[] candidates, int begin,int target,List<List<Integer>> lists,List<Integer> list) { for (int i = begin; i < candidates.length; i++) { if (i > 0 && candidates[i] == candidates[i - 1]) { continue; } int now = candidates[i]; if (now == target) { if (list == null) { list = new ArrayList<Integer>(); } List<Integer> integerList = new ArrayList<Integer>(list); integerList.add(now); lists.add(integerList); continue; } if (now * 2 <= target) { //两倍的值小于目标值 if (list == null) { list = new ArrayList<Integer>(); } List<Integer> integerList = new ArrayList<Integer>(list); integerList.add(now); combineSum(candidates,i,target - now,lists,integerList); } } }}
阅读全文
0 0
- [LeetCode]39.Combination Sum
- LeetCode --- 39. Combination Sum
- LeetCode 39.Combination Sum
- [Leetcode] 39. Combination Sum
- Leetcode-39.Combination Sum
- LeetCode 39. Combination Sum
- [LeetCode]39. Combination Sum
- 39. Combination Sum LeetCode
- [leetcode] 39. Combination Sum
- leetcode 39. Combination Sum
- 【leetcode】 39. Combination Sum
- LeetCode 39. Combination Sum
- leetcode 39. Combination Sum
- LeetCode 39. Combination Sum
- LeetCode *** 39. Combination Sum
- LeetCode 39. Combination Sum
- leetcode 39. Combination Sum
- LeetCode - 39. Combination Sum
- 微信,下一个手机云系统?
- 自定义控件(三) 源码分析measure流程
- 归并排序-c++代码实现
- 成为java顶尖程序员要读的11本书
- linux中pure-ftpd简单添加用户方法
- Leetcode 39. Combination Sum
- 看完这13张图,不得不佩服还是外国人会玩人工智能
- 进度条
- 简单六步,用数据说服你的听众
- 泡泡堂
- 【机器学习】scikit-learn朴素贝叶斯GaussianNB实例
- 基于庆科3165模块开发智能空气检测仪
- 基于DE2的VHDL六层电梯控制程序设计
- 171212 开发板-Arduino连接蓝牙调试