java combinationsum_leecode 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.

输入一个不含重复数字的候选的数字集(C)和一个目标数字(T)。我们需要找出c中的数字的不同组合,使得每一种组合的元素加和为T。

For example, 输入的候选集[2, 3, 6, 7]和目标数字7,

结果集是:

[[7],[2, 2, 3]]

想法

这道题采取了递归的思路。

递归方法的输入参数分别是,最终需要返回的结果list,暂存元素list,候选集,离目标元素和的差值,和开始遍历的起点。

每次将一个元素加入templist的时候,判断是否满足templist中的元素加和等于target,如果等于,直接将templist加入最终返回的结果集res。如果加和大于target,那么就没必要继续递归往templist中增加元素了。如果加和小于list,那么继续递归加入新的元素。

解法

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

List> res = new ArrayList>();

Arrays.sort(nums);

backtrack(res,new ArrayList<>(),nums,target,0);

return res;

}

public void backtrack(List> res,List temp,int[] nums,int remain,int start){

if(remain <0)return;

if(remain == 0)res.add(new ArrayList<>(temp));

else{

for(int i=start;i

temp.add(nums[i]);

backtrack(res,temp,nums,remain-nums[i],i);

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

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值