简体   繁体   English

java中的递归算法实现

[英]Recursive algorithm implementation in java

I am trying to write a method with the following header: 我正在尝试使用以下标头编写方法:

public static boolean difference(int[] numbers, int size, int difference) {...}

I want it to be able to determine if it is possible to choose any two integers from the list "numbers" such that the difference between them is equal to the parameter "difference". 我希望它能够确定是否可以从列表“数字”中选择任意两个整数,使得它们之间的差异等于参数“差异”。

So far I was thinking that I should create a list where the elements contain all possible combinations of the elements in list "numbers" and then fill another list of all possible difference values. 到目前为止,我一直在想我应该创建一个列表,其中元素包含列表“数字”中元素的所有可能组合,然后填充所有可能差值的另一个列表。

Then I would finally check if the parameter "difference" is inside that list. 然后我最终检查参数“差异”是否在该列表中。 If it is then it would return true. 如果是,那么它将返回true。 I also want to do this recursivly so any help would be appreciated. 我也想要递归地做这个,所以任何帮助将不胜感激。 thanks! 谢谢!

There's no need to create an entire list of differences - what if numbers[1] - numbers[0] gives the desired difference? 没有必要创建一个完整的差异列表 - 如果numbers[1] - numbers[0]给出所需的差异怎么办? You would have wasted a whole lot of time. 你会浪费很多时间。 You can just use two nested for -loops to loop over the array and check if any two numbers at distinct indexes have the desired difference; 您可以使用两个嵌套for -loops循环遍历数组,并检查不同索引处的任何两个数字是否具有所需的差异; if any do, return true and exit the method altogether, since there would be no reason to continue the loop. 如果有的话, return true并完全退出方法,因为没有理由继续循环。

I'm assuming you're trying to learn about recursion, and I'm assuming this is homework. 我假设你正在尝试学习递归,我假设这是作业。 I won't give you a code example, but I hope this helps you. 我不会给你一个代码示例,但我希望这会对你有所帮助。

Maybe you need to think about how to break your problem up into simpler sub problems. 也许您需要考虑如何将问题分解为更简单的子问题。 Perhaps instead of the harder problem of finding a pair in the list with a given difference, you could write a method that just checked whether the right difference could be found by taking the number at the start of the list and comparing it to all the other numbers in the list. 也许不是在列表中找到具有给定差异的对的更难的问题,您可以编写一种方法,通过获取列表开头的数字并将其与所有其他数据进行比较来检查是否可以找到正确的差异。列表中的数字。

Then, maybe you could modify your method so that it pops off the number at the start, checks against the rest of the list, and if unsuccessful calls itself with the rest of the list? 然后,也许你可以修改你的方法,以便它在开始时弹出数字,检查列表的其余部分,如果不成功调用自己与列表的其余部分? Think about what to return. 想想要回归什么。 If you get this far you've done it. 如果你走到这一步,你已经做到了。 Watch out for what happens when you run out of elements left in the list. 注意当列表中剩余的元素用尽时会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM