java递归:数字的最佳集合
给定一个整数数组和另一个整数。如何使用递归从该数组中查找整数集合,以便集合的总和最接近给定整数? 例如,给定数组:1,2,3,且给定整数为5,则该方法返回2,3; 另一个例子:如果给定的数组是:35,14,45,3,并且给定的整数是50,那么该方法返回35和14。这看起来像是一个家庭作业,所以我不放任何代码,而是尝试解释算法。 想象一下,你得到了java递归:数字的最佳集合,java,arrays,recursion,Java,Arrays,Recursion,给定一个整数数组和另一个整数。如何使用递归从该数组中查找整数集合,以便集合的总和最接近给定整数? 例如,给定数组:1,2,3,且给定整数为5,则该方法返回2,3; 另一个例子:如果给定的数组是:35,14,45,3,并且给定的整数是50,那么该方法返回35和14。这看起来像是一个家庭作业,所以我不放任何代码,而是尝试解释算法。 想象一下,你得到了[35,14,45,3]和50 1. First sort the array in descending order: [45, 35, 14,
[35,14,45,3]
和50
1. First sort the array in descending order: [45, 35, 14, 3]
2. You should remove the 1st item in the array and take it or leave it
3. So you'll have two smaller problems:
[35, 14, 3] and 5 (45 is taken)
[35, 14, 3] and 50 (45 is left)
4. To cut story short keep the best score so far: 5 in your case.
It let you trim some negative value branches
[35, 14, 3] and 5 (45 is taken) is the best so far
5. If the array is not empty, go to the step 2
整个痕迹是
[35, 14, 3] and 5 (45 taken) // the best score so far
[14, 3] and -30 (45, 35 taken) // trim: worse than the best score so far
[14, 3] and 5 (45 taken)
[3] and -9 (45, 14 taken) // trim
[3] and 5 (45 taken)
[] and 2 (45, 3 taken) // the best score so far
[] and 5 (45 taken)
[35, 14, 3] and 50 (nothing taken)
[14, 3] and 15 (35 taken)
[3] and 1 (35, 14 taken) // the best score so far
[] and -2 (35, 14, 3 taken)
[3] and 15 (35 taken)
[] and 12 (35, 3 taken)
...
最后,到目前为止,1
的最好分数是采用(35,14)
的解决方案。
在实现时,您可以进行两个递归调用:一个用于“take”,另一个用于“leave”。这是一个家庭作业问题吗?家庭作业?请把你试过的贴出来。谢谢!这是一个赋值,我试着这样做:对于数组中的每个元素,调用递归方法(计算最佳值),数组中不包含该元素,相应的整数减去该元素……然后我就无法计算出基本情况下返回的值。递归对我来说是相当困难的。