C 正方形中矩形的最小割数
任务是找到正方形中矩形的最小切割数。我编写了一个递归函数来实现这一点,但关键是要使用动态编程来编写它。我在纸上写了这个矩阵,但还是发现写代码很困难。。此处a和b是矩形的尺寸:C 正方形中矩形的最小割数,c,dynamic-programming,C,Dynamic Programming,任务是找到正方形中矩形的最小切割数。我编写了一个递归函数来实现这一点,但关键是要使用动态编程来编写它。我在纸上写了这个矩阵,但还是发现写代码很困难。。此处a和b是矩形的尺寸: int minimalNumOfCuts(int a, int b) { if (a==b) return 0; int result; if (a<b) result = 1+minimalNumOfCuts(b-a,a);//found a square with side
int minimalNumOfCuts(int a, int b)
{
if (a==b) return 0;
int result;
if (a<b)
result = 1+minimalNumOfCuts(b-a,a);//found a square with side a, so I add 1 and recurs on
else result = 1+minimalNumOfCuts(a-b,b);//found a square with side b
return result;
}
intminimumofcuts(inta,intb)
{
如果(a==b)返回0;
int结果;
如果(a您使用欧几里德算法(这是您在那里尝试的)遍历矩形,并计算切割,则递归函数可能实现这一点,下面是一个可能的实现,它将计数器指针作为要在内部递归中更改的函数的参数传递:
编辑:
对于您的表格,只需循环浏览以下值:
此示例使用相同的递归函数计算高度为1到5、长度为1到4的矩形的切割数
在那里你可以检查结果
请注意,您的表格中有一些不精确的地方,例如,一个3边和4边的矩形只需要3次切割。请详细说明这个问题,并使用有意义的变量名称,这样我们就可以了解您的代码和什么是“动态编程”@pm100,根据标签的描述判断动态编程是一种算法技术e为了有效地解决包含许多重叠子问题的递归结构问题
OP可能需要一个递归方法,尽管它不太清楚。标记文本对我来说像bs,OP代码是recursive@pm100哈哈,既然你没有给我贴标签,我几乎错过了你的精彩评论,那太可惜了。我不得不同意你的看法你需要评估。
#include <stdio.h>
#include <stdlib.h>
void minimalNumOfCuts(int side1, int side2, int *count);
int main() {
int side1 = 3, side2 = 5, count = 0;
minimalNumOfCuts(side1, side2, &count);
printf("Height %d Length %d - %d cuts\n", side1, side2, count);
return EXIT_SUCCESS;
}
void minimalNumOfCuts(int side1, int side2, int *count) {
if (side1 == side2) {
return;
}
if (side1 > side2) {
side1 -= side2;
}
else {
side2 -= side1;
}
(*count)++;
minimalNumOfCuts(side1, side2, count); //recursive call
}
Height 3 Length 5 - 3 cuts
#define MAX_HEIGHT 5
#define MAX_LENGHT 4
int main() {
int count = 0;
for (int i = 1; i < MAX_HEIGHT + 1; i++) {
for (int j = 1; j < MAX_LENGHT + 1; j++) {
minimalNumOfCuts(i, j, &count);
printf("Height %d Length %d - %d cuts\n", i, j, count);
count = 0;
}
}
return EXIT_SUCCESS;
}
Height 1 Length 1 - 0 cuts
Height 1 Length 2 - 1 cuts
Height 1 Length 3 - 2 cuts
Height 1 Length 4 - 3 cuts
Height 2 Length 1 - 1 cuts
Height 2 Length 2 - 0 cuts
Height 2 Length 3 - 2 cuts
Height 2 Length 4 - 1 cuts
Height 3 Length 1 - 2 cuts
Height 3 Length 2 - 2 cuts
Height 3 Length 3 - 0 cuts
Height 3 Length 4 - 3 cuts
Height 4 Length 1 - 3 cuts
Height 4 Length 2 - 1 cuts
Height 4 Length 3 - 3 cuts
Height 4 Length 4 - 0 cuts
Height 5 Length 1 - 4 cuts
Height 5 Length 2 - 3 cuts
Height 5 Length 3 - 3 cuts
Height 5 Length 4 - 4 cuts