gpt4 book ai didi

复杂的C程序

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

C 代码,用于在给定的符号集上生成长度最多为 k 的所有字符串。任何字符串中不得重复任何符号。例子:取英文字母中的6个小写符号{a,b,c,d,e,f},k=3;打印按字典顺序排序的输出的前 25 个字符串。

谁能帮帮我吗?

编辑

# include <stdio.h>
# include <conio.h>


void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}


void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j));
}
}
}


int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}

然而,这将给出所有字母的排列。用空格替换要参数化的字母似乎并不能解决问题!即使用可置换的空格重复调用 permute 听起来也效率不高。

最佳答案

假设您的字符池已排序并且没有重复(可能需要一些预处理),则按字典顺序生成所需的字符串是自动的(按照我想到的方法)。

查看可以从“ABC”生成的所有非空字符串的简短示例,但有限制:

A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA

您需要跟踪

  1. 您选择了多少个字符、哪些字符以及按什么顺序:以及 intchar[]
  2. 您仍可以选择多少个字符以及哪些字符:intbool[](或 char[] int[])
  3. 您还需要输出多少个字符串,因为它将在递归调用中修改:一个 int*

    void 排列(char *pool, int pool_length, int num_picked, char *stringy, bool *picked, int max_length, int *strings_left) {

    int i;
    for(i = 0; *string_left > 0 && i < pool_length; ++i) {
    if (pool[i] may be picked) {
    // 1. pick that as the num_picked + 1st character
    // 2. output and decrement *strings_left
    // 3. recur
    // 4. unpick pool[i]
    }
    }

    }

我希望这对您有所帮助,但我并没有放弃太多。

关于复杂的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010374/

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