對一個字符數組進行全排列

#include <stdio.h>
#include <stdlib.h>
void swapArrayElements(char a[], int lhs, int rhs)
{
     char temp;
     temp = a[lhs];
     a[lhs] = a[rhs];
     a[rhs] = temp;
}
void perm(char a[], int start, int end)
{
     int i, j;
     if (start == end){
               //輸出排列結果
               for (j = 0; j <= end; j++)
                   putchar(a[j]);
               putchar('/n');
               return;
     } else{
           
            for (i = start; i <= end; i++){
                //將數組片段的各元素與首元素交換
                swapArrayElements(a, start, i);
               
                //對交換後的,去掉首元素的數組片段進行全排列
                perm(a, start+1, end);
               
                //交換回來
                swapArrayElements(a, start, i);
            }
     }
}
main()
{
      char a[] = {'A', 'B', 'C', 'D'};
      perm(a, 0, 3);
      system("pause");
}
發佈了434 篇原創文章 · 獲贊 93 · 訪問量 154萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章