【问题标题】:C - Printing combinations in an array or listC - 在数组或列表中打印组合
【发布时间】:2025-12-04 22:35:02
【问题描述】:

我编写了一个程序,它接收一串字符,并打印出它们的所有可能组合。但是,有没有办法将每个组合记录在列表或数组中,而不仅仅是在屏幕上打印它们?因为我需要能够操纵一些连击,而不仅仅是看着它们。

void swap( char *a, char *b ){
    char tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

void permutation( char *c, int d, int e ){
    int f;

    if( d == e )
        printf( "%s\n", c );
    else{
        for( f = d; f <= e; f++ ){
            swap( ( c + d ), ( c + f ) );
            permutation( c, d + 1, e );
            swap( ( c + d ), ( c + f ) );
        }
    }
}

int main(){
    char wordInput[25];
    int len, arrLen, f;

    printf( "\nEnter text: " );
    gets( wordInput );
    len = strlen( wordInput );
    arrLen = len - 1;

    permutation( wordInput, 0, arrLen );

    return 0;
}

【问题讨论】:

  • 提示:假设我们有一个单词是 k 字母长,那么排列的数量将是 k! = k(k-1)(k-2)...(3)(2)(1) 所以你需要一个字符串数组(每个 k 字母长),它是大小!因此,首先使用 strlen 计算长度,然后使用 malloc 分配数组,然后使用您喜欢的任何内容(递归可以)运行排列以填充数组并瞧。尝试使用此提示创建程序。如果您遇到问题,将进一步提供帮助:-)

标签: c arrays printing permutation


【解决方案1】:

只需将 permuation() 更改为以下内容:

int permutation( char *c, int d, int e, int n, char **permuted_strings)

其中 n 是数组 permuted_strings 中下一个未使用元素的索引。 permuted_strings 应该是一个 k 数组!元素,如果您的字符串长度为 k,如注释中所示。如果满足您的条件 (d == e),那么您应该将字符串保存在 permuted_strings[n] 并将 n 增加 1 并将该值作为 n 的新值返回。 permutation() 函数应该始终返回 n 的当前值,并且在调用它时 n 应该重置为 permutation() 的返回值,以便后续对 permutation() 的调用知道 n 的正确值,即到哪里存储下一个字符串。

【讨论】:

    最近更新 更多