【发布时间】:2017-10-29 00:32:18
【问题描述】:
问题:http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
我的代码在:http://ideone.com/HGXk3t
我尝试解决递归问题,但得到了意想不到的结果。 对于杆切割问题,我最多调用两个相同的递归函数:一个使用该索引,另一个不使用该索引的价格。 但答案不是它应该是的。 提前致谢。
#include<stdio.h>
// A utility function to get the maximum of two integers
int max(int a, int b) { return (a > b)? a : b;}
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
int cutRod(int price[], int n, int i)
{
if(n<1 || i==0)
return 0;
return max(price[i-1] + cutRod(price,n-(i+1),i), cutRod(price,n,i-1));
}
/* Driver program to test above functions */
int main()
{
int arr[] = {17, 17, 1};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %d\n", cutRod(arr, size, size));
getchar();
return 0;
}
【问题讨论】:
-
使用 std:: 向量,std::max。不要使用 stdio.h 和 limits.h。
-
@Rahul——选择一种语言; C 和 C++ 不一样。
-
@manni66-- 发布的代码是 C。我认为这里不需要
limits.h,但为什么不应该使用stdio.h?毕竟printf()需要。 -
limits.h不需要,除非您使用INT_MIN作为算法的负权重。 -
我删除了limits.h。我之前使用的是 INT_MIN,但后来删除了。