gpt4 book ai didi

c - 动态规划失败的测试用例

转载 作者:行者123 更新时间:2023-11-30 17:26:28 24 4
gpt4 key购买 nike

问题定义:

计算一组中最长的子集对,其总和为 10。一旦确定了一个对,这 2 个数字就不能用于形成其他对。输出应该是一个数字,表示此类对中涉及的数字的计数。

输入:1 {1,2,8,9,1,9,1,9} 答案:6(3 对,6 个数字,索引 = {0,7},{3,6},{4, 5})

输入:2 {5,5,5,5,5,5,5,5} Ans:8(4 对,8 个数字,索引 = {0,7},{1,6},{2, 5},{3,4})

输入:3 {2,4,3,7,3,8,6,7} 答案:4(2 对,4 个数字,索引 = {0,5},{3,4} 或 {0, 5}、{2,3} 或 {2,7}、{3,4} 或 {1,6}、{2,3} 或 {1,6}、{3,4})

我编写了以下代码:

#include <stdio.h>
#include <stdlib.h>

#define ARRAYSIZE 10
#define SUM 10

int d[ARRAYSIZE][ARRAYSIZE];
int count = 0;
int final[ARRAYSIZE/2];
int reset = 0;
int subset_to_sum(int a[], int m, int n, int sum)
{
//printf("%d %d %d \t",m,n,d[m][n]);
if (m >= n)
return 0;
if (d[m][n] != -1)
return d[m][n];

if (a[m]+a[n] == sum)
{
d[m][n] = 1;
count = count+1;
//printf("%d\n",count);
if (m+1>=n-1)
{
final[reset] = count;
reset = reset+1;
count = 0;
}
else
final[reset] = count;
return 1+subset_to_sum(a, m+1, n-1, sum);
}
else if (a[m] > sum)
return subset_to_sum(a, m+1, n, sum);
else if(a[n] > sum)
return subset_to_sum(a, m, n-1, sum);
else
return (subset_to_sum(a, m+1, n, sum)+subset_to_sum(a, m, n-1, sum)+subset_to_sum(a, m+1, n-1, sum));
}

int main(void)
{
int i = 0;
int j;
int inc;

//int set[] = {1,2,8,9,1,9,1,9};
//int set[] = {1,2,8,4,5,9,1,9};
//int set[] = {2,4,3,7,3,8,6,7};
//int set[] = {5,5,5,5,5,5,5,5};
//int set[] = {25,35,45,5,6,7,8,9};
//int set[] = {1,2,3,4,5,6,7,8,9,10};

for(i=0;i<ARRAYSIZE;i++)
{
for(j=0;j<ARRAYSIZE;j++)
{
d[i][j] = -1;
}
}
printf("\n");
//printf("Total Pairs making sum %d is : %d\n",SUM,subset_to_sum(set, 0, ARRAYSIZE-1, SUM)*2);
subset_to_sum(set, 0, ARRAYSIZE-1, SUM);

int max = 0;
for(i=0;i<4;i++)
{
if(final[i]>max)
max = final[i];
}
printf("Subset Pairs making sum %d is: %d\n",SUM,max*2);
return 0;
}

我的代码对于输入失败:{1,2,3,4,5,6,7,8,9,10}。有人可以指出我方法中的缺陷吗?

谢谢!

最佳答案

我稍微修改了你的代码,你可以尝试一下吗:

int subset_to_sum(int a[], int m, int n, int sum)
{

if (m >= n)
return 0;

if (a[m]+a[n] == sum)
return 1+subset_to_sum(a, m+1, n, sum) + subset_to_sum(a, m, n-1, sum);
else
return subset_to_sum(a, m+1, n, sum) + subset_to_sum(a, m, n-1, sum);
}

关于c - 动态规划失败的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com