gpt4 book ai didi

c++ - 优化子集和实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:45 25 4
gpt4 key购买 nike

我正在使用以下代码解决子集和问题的变体。该问题需要从更大的集合(超集)中生成 11 个整数的子集,并检查它是否与特定值(endsum)匹配。

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

int endsum = 0, supersetsize = 0, done = 0;
int superset[] = {1,30,10,7,11,27,3,5,6,50,45,32,25,67,13,37,19,52,18,9};
int combo = 0;

int searchForPlayerInArray(int arr[], int player) {
for (int i=0; i<11; i++) {
if (arr[i] == player) {
return 1;
}
}
return 0;
}

int sumOfArray(int arr[]) {
int res = 0;
for (int i=0; i<11; i++) {
res+=arr[i];
}
return res;
}

void printArray(int arr[], int arrSize) {
for (int j=0; j<arrSize; j++) {
printf("%2d ",arr[j]);
}
printf("= %d\n",endsum);
}

void permute(int subset[], int pos, int sspos) {
if (done) { //when a correct solution has been found, stop recursion
return;
}
if (sspos == supersetsize) { // out of possible additions
return;
}
if (pos == 11) { //is the current subset 11 ints long?
int res = sumOfArray(subset);
combo++;
if (res == endsum) { //if the sum of the array matches the wanted sum, print
printArray(subset,11);
done = 1;
}
return;
}
for (int i=sspos; i<supersetsize; i++) {
//assert(pos < 11);
//assert(i+1 <= supersetsize);
subset[pos] = superset[i];
permute(subset,pos+1,i+1);
}
}

int main(void) {
endsum = 110;
supersetsize = 20;
int *arr;
arr = malloc(supersetsize*sizeof(int));
int i;
for (i=0; i<supersetsize; i++) {
arr[i] = 0;
}

permute(arr,0,0);

printf("Combinations: %d",combo);
return 0;
}

虽然此解决方案适用于小型超集 (<15),但速度慢且效率低下,因为它会生成所有可能的排列,而不仅仅是唯一的排列。我如何优化它以仅生成唯一的子集?

编辑:应大众需求添加的完整源代码。

最佳答案

仅生成唯一子集的一种方法是按顺序添加超集中的元素,并使用附加参数permute(例如。supersetPos)来指示位置你在超集中。这会生成唯一的排序排列。

编辑:AFAIK 在您的样本上正确运行的代码:

#include <stdio.h>

int superset[] = {
1, 30, 10, 7, 11,
27, 3, 5, 6, 50,
45, 32, 25, 67, 13,
37, 19, 52, 18, 9
};
int supersetsize = 20;
int endsum = 110;
int done = 0;

int sumOfArray(int array[]) {
int sum = 0;
for(int i = 0; i < 11; i++)
sum += array[i];
return sum;
}

void permute(int subset[], int pos, int sspos) {

if (pos == 11) { //is the current subset 11 ints long?
if (sumOfArray(subset) == endsum) { //if the sum of the array matches the wanted sum, print
for (int j=0; j<11; j++) {
printf("%d ",subset[j]);
}
printf("\n");
done = 1;
}
return;
}
for (int i=sspos; i<supersetsize; i++) {
subset[pos] = superset[i];
permute(subset,pos+1,i+1);
if (done) { //when a correct solution has been found, stop recursion
return;
}
}

}
int main() {
int subset[11] = {0};
permute(subset, 0, 0);
}

关于c++ - 优化子集和实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39554444/

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