java 回溯_Java-0011-递归回溯小试牛刀

2016.7.22

groupSum

Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? This is a classic backtracking recursion problem. Once you understand the recursive backtracking strategy in this problem, you can use the same pattern for many problems to search a space of choices. Rather than looking at the whole array, our convention is to consider the part of the array starting at index start and continuing to the end of the array. The caller can specify the whole array simply by passing start as 0. No loops are needed -- the recursive calls progress down the array.

groupSum(0, [2, 4, 8], 10) → true

groupSum(0, [2, 4, 8], 14) → true

groupSum(0, [2, 4, 8], 9) → false

public boolean groupSum(int start,int[] nums,int target){

}

题意:

给定一个int型数组,你可以选择数组的中的数相加来得到给定的目标数吗?这是一个经典的回溯递归问题。一旦你在这个问题上了解了递归回溯策略,你可以使用相同的模式为许多问题提供一个搜寻空间的解决方法。我们的惯例是考虑从索引开始到结束的数组部分,而不是看整个数组。调用方可以简单地通过从0开始指定整个数组。没有循环是必要的-递归调用的数组的进度。

即,从start索引开始从数组nums中选择若干个数来相加得到一个target的值,能则返回true,不能则返回false。

整个问题的关键:怎么返回分支口并进入另一个分支

思路:

groupSum方法的返回类型是boolean类型,我们可以先加上索引对应的数组数,然后用groupSum将剩下的对应参数传入,并作为if的表达式,这样它返回的就是加过这个数后还能否得到剩下的target。

如果能则返回true;不能则不加这个数,并将索引加1后传入groupSum。

在方法的最前面写判断递归结束的条件和结果。

public boolean groupSum(int start,int[] nums,int target){

if(target==0)

return true;

if(start==nums.length)

return false;

if(groupSum(start+1,nums,target-nums[start])){

return true;

}

else{

return groupSum(start+1,nums,target);

}

}

可能看懂了代码的意思,但还不是很理解它到底是怎么递归怎么回溯的。

下面我做了一个图,帮助大家看懂

图片很大,但显示问题网页上放不了多大,建议下载递归回溯groupSum下来看

8f5031905bc3

递归回溯groupSum500.jpg

思路更清晰的代码(2016.7.30补)

public boolean groupSum(int start,int[] nums,int target){

if(target==0)

return true;

if(start==nums.length)

return false;

return groupSum(start+1,nums,target-nums[start])||groupSum(start+1,nums,target);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值