c - 该算法在 Big-O 表示法(字符串排列)中的顺序是什么?

标签 c string performance big-o permutation

以下算法的大 O 表示法的性能如何? 这是我编写的函数,用于打印字符串的所有排列。 我知道对于长度为 n 的输入有 n!不同的排列。 有人可以解释为得出这样的结论所做的分析吗?

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

void permute(char* output, char* input, int used[], int index, int length){
    int i;

    if (index == length) {
        printf("%s\n", output);
        return;
    }

    for (i=0; i< length; i++){
        if (! used[i] ){
            output[index] = input[i];
            used[i] = 1;
            permute(output, input, used, index+1, length);
            used[i] = 0;
        }
    }
}


int main(){
    char input[] = "abcd";
    char* output;
    int length = strlen(input);
    int* used;

    // Allocate space for used array
    used = (int*) malloc (sizeof (int)* length);
    memset (used, 0, sizeof (int)* length);

    // Allocate output buffer
    output = (char*) malloc ( length+1);
    if (!output) return 1;
    output[length] = '\0';

    // First recursive call
    permute(output, input, used, 0, length);

    free (output);

    return 0;
}

最佳答案

I know for an input of length n there are n! different permutations.

你刚刚回答了你自己的问题

关于c - 该算法在 Big-O 表示法(字符串排列)中的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13672175/

相关文章:

c - 从钩子(Hook)函数返回挂起

c - 在 C 中评估字符串中的类型标识符 (%d)

java - 单行字符串连接的速度差异

python - 提高 C++ 正则表达式替换性能

Mysql subselect 非常慢(似乎没有使用索引)

c - 替代 gethostbyname 我可以在哪里选择 DNS 服务器?

c - 为什么以及在何种意义上 pthread_t 是不透明类型?

python - 如何在不同时替换所有子字符串的情况下替换子字符串? Python

javascript - 为什么 getBoundingClientRect 在 IE8 中很慢?

c - 当我有 main1、main2 和 main 时,如何执行 main1?