C語言實現的全排列算法
#include <stdio.h> /************************************************************************/ /* 功能:實現兩個整形參數值交換 /* 參數: /* lhs--int類型的指針,指向待交換數1的地址 /* rhs--int類型的指針,指向待交換數2的地址 /************************************************************************/ void Swap(int *lhs, int *rhs) { int t = *lhs; *lhs = *rhs; *rhs = t; } /************************************************************************/ /* 功能:實現全排列功能 /* 參數: /* source--整數數組,存放需要全排列的元素 /* begin --查找一個排列的開始位置 /* end --查找一個排列的結束位置,當begin=end時,表明完成一個排列 /************************************************************************/ void FullPermutation(int source[], int begin, int end) { int i; if (begin >= end) // 找到一個排列 { for (i = 0; i < end; i++) { printf("%d", source[i]); } printf("\n"); } else// 沒有找完一個排列,則繼續往下找下一個元素 { for (i = begin; i < end; i++) { if (begin != i) { Swap(&source[begin], &source[i]); // 交換 } // 遞歸排列剩餘的從begin+1到end的元素 FullPermutation(source, begin + 1, end); if (begin != i) { Swap(&source[begin], &source[i]); // 回溯時還原 } } } } int main() { int source[30]; int i, count; scanf("%d", &count); // 初始化數組 for (i = 0; i < count; i++) { source[i] = i + 1; } FullPermutation(source, 0, count); return 0; }
最後更新:2017-04-03 18:52:03