Generate list of all possible permutations of a string

后端 未结 30 2843
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 15:39

    It's better to use backtracking

    #include 
    #include 
    
    void swap(char *a, char *b) {
        char temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }
    
    void print(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);
                print(a, i + 1, n);
                swap(a + i, a + j);
            }
        }
    }
    
    int main(void) {
        char a[100];
        gets(a);
        print(a, 0, strlen(a) - 1);
        return 0;
    }
    

提交回复
热议问题