码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] Combination Sum

时间:2015-07-13 14:14:44      阅读:313      评论:0      收藏:0      [点我收藏+]

标签: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.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , 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,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 


题意:

给定一组整数(C)和一个目标值 (T),从(C)中找出所有的存在且唯一的组合,使他们的和等于(T)。

同一个重复数字可以在C无限次的选择。 

注意:

     1.所有的数字包括目标值都是非负整数.

     2. 组合中的元素(a1a2, … , 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!