combination sum java_leetcode 39 Combination Sum --- java

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.

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]

]

这道题的意思是给定一个数组和一个目标数,求出用数组内的数字(可以重复)相加等于目标数的所有组合

先上代码

public class combinationSum {

public List> combinationSum(int[] candidates, int target) {

List> result = new ArrayList>();

Arrays.sort(candidates);

getResult(candidates,target,0,result,new ArrayList());

return result;

}

public void getResult( int[] candidates, int target,int pos, List> result,List ans){

for( int i = pos;i

if( target == candidates[i]){

ans.add(candidates[i]);

result.add(new ArrayList(ans));

ans.remove(ans.size()-1);

return;

}

else if(target > candidates[i]){

ans.add(candidates[i]);

getResult(candidates,target-candidates[i],i,result,ans);

ans.remove(ans.size()-1);

}else

return ;

}

}

/*

* 1.给出一个数组以及一个目标数,求出用数组中的数相加等于目标数的所有结果(数组中的数可以重复);

* 2.78+21

*/

}

主要是用递归的方法,如果小与target那么接着加,直到等于target或者大于target为止。有点类似于八皇后。

例如,给定{2,2,3}和7  由于可以重复数字,(其实相当于{2,3}和{7}),先进行排序

那么     2<7    -------->   (2+2)<7      -------->   (2+2+2)<7  -------->   (2+2+2+2)>7    舍去 ,由于+2已经大于7,那么剩下的也都会大于7. 之后的+3就可以舍去了

-------->   (2+2+2+3)>7

-------->   (2+2+3)=7                获得一个答案,之后的数字也不用计算,因为肯定会比7要大

-------->   (2+3)<7      -------->   (2+3+3)>7                 舍去

3<7    -------->   (3+3)<7      -------->   (3+3+3)>7                 舍去

这就得到了所有的答案。

但是结果并不是特别理想,然后做下列调整:

1.尽量减少new ArrayList()的操作,新建对象的操作会增加运行时间和内存。

2.也可以使用DP,但是就结果而言,还是递归比较好。

3.最后发现,如果不用List而改用数组,那么就会击败所有用户,达到最快

public class Solution {

public List> combinationSum(int[] candidates, int target) {

List> result = new ArrayList>();

Arrays.sort(candidates);

getResult(candidates,target,0,result,new int[target],0);

return result;

}

public void getResult( int[] candidates, int target,int pos, List> result,int[] ans,int num){

for( int i = pos;i

if( target == candidates[i]){

List aa = new ArrayList();

for( int ii =0; ii

aa.add(ans[ii]);

aa.add(candidates[i]);

result.add(aa);

return;

}

else if(target > candidates[i]){

ans[num] = candidates[i];

getResult(candidates,target-candidates[i],i,result,ans,num+1);

}else

return ;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值