感谢博主的分享:算法-动态规划 Dynamic Programming
这里是我写的递归版本的钢条切割的代码,其中需要注意的是cut函数之后MIN直接用了p数组的长度10,不用sizeof(p)/sizeof(p[0]),因为C中默认传入函数的数组会衰减为指针,得不到原来的长度。参考:c - Length of array in function argument - Stack Overflow
// Online C compiler to run C program online
#include <stdio.h>
#include <string.h>
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
int cut(int p[10],int n)
{
if(n==0)
return 0;
int q=0;
int up_b = MIN(10, n); // set the length of the array p to 10 because it would be converted to pointer when passed into a sub-function
//printf("n is %d, sizeof(p)/4 is %d, up_b is %d\n", n, 10, up_b);
for(int i=0;i<up_b;i++)
{
q=MAX(q, p[i]+cut(p, n-i-1));
}
return q;
}
int main() {
// Write C code here
int p[10] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
printf("p length is %d\n", sizeof(p)/4);
int n;
scanf("%d", &n);
printf("n is %d\n", n);
int q = cut(p, n);
printf("q is %d\n", q);
return 0;
}