[LeetCode][Java] Combination Sum
2015-07-13 11:16
453 查看
题目:
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wherethe 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.Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
题意:
给定一组整数(C)和一个目标值 (T),从(C)中找出所有的存在且唯一的组合,使他们的和等于(T)。同一个重复数字可以在C无限次的选择。
注意:
1.所有的数字包括目标值都是非负整数.
2. 组合中的元素(a1, a2,
… , ak)为升序排列。(ie, a1 ≤ a2 ≤
… ≤ ak).
3.最终的解中组合不能出现重复.
比如,给定一组整数集
2,3,6,7和目标值
7,
一个解集为:
[7]
[2, 2, 3].
算法分析:
该题是一个求解循环子问题的题目,采用递归进行深度优先搜索。基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的。AC代码:
/** * The first impression of this problem should be depth-first search(DFS). To solve DFS problem, recursion is a normal implementation. * Note that the candidates array is not sorted, we need to sort it first. */ public class Solution { List<List<Integer>> result; List<Integer> solu; public List<List<Integer>> combinationSum(int[] candidates, int target) { result = new ArrayList<>(); solu = new ArrayList<>(); if(candidates == null || candidates.length == 0) return result; Arrays.sort(candidates); getCombination(candidates, target, 0, 0); return result; } public void getCombination(int[] candidates, int target, int sum, int level) { if(sum>target) return; if(sum==target) { result.add(new ArrayList<>(solu)); return; } for(int i=level;i<candidates.length;i++) { sum+=candidates[i]; solu.add(candidates[i]); getCombination(candidates, target, sum, i); solu.remove(solu.size()-1); sum-=candidates[i]; } } }
相关文章推荐
- Java基础知识总结之多线程
- jdk 5并发包中CopyOnWrite类的用法
- java单例模式
- Java中数据相互转换
- Java之list
- 转!!为什么要java环境变量配置?
- javaweb项目开启ssi包含
- 解决Eclipse导入ApiDemos后R.java不自动生成的问题
- Spring MVC 学习 之 - URL参数传递
- Java Collection 接口、Set 接口、List 接口基本操作 练习
- Java获取当前日期前一周、前一个月、当年的时间、两个日期间的间隔天数
- 开源 java CMS - FreeCMS2.1公布
- java操作MySQL数据事务的简单学习
- JavaJdbc ORA-12505错误解决方法
- Spring2.5.6 和Spring3.0.5所有jar下载地址
- MyEclipse常用快捷键
- [LeetCode][Java] Count and Say
- Java中的基本数据类型和引用数据类型的内存模型
- win7下JDK环境变量配置
- == !=比较的是内存地址 字符串用equals比较