[LeetCode
来源:互联网 发布:股市分析软件 编辑:程序博客网 时间:2024/06/07 02:02
1 问题
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]]
2 分析
如果对输入不做处理,所有可能出现的数字组合有 target
比较,时间复杂度是指数级别的。
但是该问题蕴含着数字的大小、相等关系,因此需要利用这种内在的数字关系来提高算法的运行效率。
为此,将输入的数组进行排序,排序算法的时间复杂度是
设输入的数组用 target
相等的组合,层数等于可能的组合中的数字个数。令
- 如果
Sn≤target 该节点存在子节点,继续按照图示规律访问子节点; - 如果
Sn>target ,该节点为叶子,应当回溯回父节点。
在所有可能的组合遍历完成后,与target
相等的组合会被记录下来。
该算法的时间复杂度为树中所有节点的数目,与题目所给输入值有关。
3 代码
递归+回溯:
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<List<Integer>>(); getResult(result, new ArrayList<Integer>(), candidates, target, 0); return result; } private boolean getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){ if(target == 0){ result.add(new ArrayList<Integer>(cur)); return true; }else if(target < 0){ return false; }else{ for(int i = start; i < candidates.length && target >= candidates[i]; i++){ cur.add(candidates[i]); boolean res = getResult(result, cur, candidates, target - candidates[i], i); if(!res){ return false; } cur.remove(cur.size() - 1); } return true; } }}
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- MongoDB C100DEV 认证考试
- Android常用的数据结构
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- 牛腩新闻错误总结
- python + Mongodb小试
- [LeetCode
- backtrace 调试 代码执行的路径(调用栈)
- python~crush之convert工具
- File文件使用
- Hibernate关联关系映射---1对1
- Spring-Data-Redis之实例Demo
- Python中单词大小写正规化
- java并发底层实现原理
- Android 数据结构以及常用的算法