(java)leetcode-39

Combination Sum

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时,将数放入list中,下一次对该list进行添加时,只能添加大于或等于该数的值,这样就能够避免说重复。
(2)就是每次将某个数添加到list中时,要让target减去相应的值作为新的target。
(3)针对(1)我们可以筛选,当当前的数大于target/2时,不添加到list中。
(4)当当前的值 == target时,添加到list中,并将该list添加到result中。

public class Solution {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
	public List<List<Integer>> combinationSum(int[] candidates, int target) 
	{
		Arrays.sort(candidates);
		findanswer(0,new ArrayList<Integer>(),candidates,target);
        return result;
    }
	public void findanswer(int index,List<Integer>ans,int[] candidates,int target)
	{
		while(index < candidates.length && candidates[index]<= target)
		{
		    //添加该数,并更新target
			if(candidates[index] <= target/2)
			{
				List<Integer> l1 = new ArrayList<Integer>(ans);
				l1.add(candidates[index]);
				findanswer(index,l1,candidates,target-candidates[index]);
			}
			//找到满足条件的,更新list,并添加到result中
			if(candidates[index] == target)
			{
				List<Integer> l1 = new ArrayList<Integer>(ans);
				l1.add(candidates[index]);
				result.add(l1);
			}
			index++;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值