标签:leetcode java combination sum
Given a set of candidate numbers (C) 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.
For example, given candidate set 2,3,6,7
and 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]; } } }
版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java] Combination Sum
标签:leetcode java combination sum
原文地址:http://blog.csdn.net/evan123mg/article/details/46860171