递归实现全排列

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

static void swap(char* pchar1, char* pchar2) {    //交换数组的两个数
    char tmp = *pchar1;
    *pchar1 = *pchar2;
    *pchar2 = tmp;
}

void permutation(char* pchar, int begin, int length) {
    int i;
    if(begin == length) {  //当只剩下一个元素时,打印数组
        printf("%s\n", pchar);
        return;
    }
    
    for(i = begin; i <= length; i++) {
        swap(&pchar[begin], &pchar[i]);
        permutation(pchar, begin+1, length);
        swap(&pchar[begin], &pchar[i]);
    }
}

int main() {
    char arr[] = "abc";
    permutation(arr, 0, strlen(arr)-1);
}

 

posted @ 2016-03-19 10:40  没有梦想的小灰灰  阅读(155)  评论(0编辑  收藏  举报