// 输出全排列
// author: kennie #include<iostream> template<typename T> void swap(T *, T *); template<typename T> void printArr(T [], int len); template<typename T> void permutation(T [], int, int, int); template<typename T> void swap( T *a, T *b ) { T tmp; tmp = *a; *a = *b; *b = tmp; } template<typename T> void printArr( T arr[], int len ) { for ( int i = 0; i < len; i++ ) { std::cout << arr[i] << "\t" ; } std::cout << std::endl; } template<typename T> void permutation( T arr[], int len, int startIndex, int endIndex ) // 递归求解全排列 { if ( startIndex > endIndex ) // 递归出口 { printArr( arr, len ); } else { for ( int j = startIndex; j <= endIndex; j++ ) // 依次交换数组元素与数组首元素 { swap( &arr[j], &arr[startIndex]); permutation( arr, len, startIndex+1, endIndex ); // 除去当前元素,剩余元素的全排列 swap( &arr[j], &arr[startIndex]); } } } int main() { // test int intArr [] = { 1, 2, 3 }; int len = sizeof ( intArr ) / sizeof ( int ); std::cout << "test int" << std::endl; permutation( intArr, len, 0, len-1 ); std::cout << std::endl; char charArr[] = { 'a', 'b', 'c', 'd' }; int len2 = sizeof ( charArr ) / sizeof( char ); std::cout << "test char" << std::endl; permutation( charArr, len2, 0, len2-1 ); std::cout << std::endl; return 0; }
// main output as follow:
test int 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2 test char a b c d a b d c a c b d a c d b a d c b a d b c b a c d b a d c b c a d b c d a b d c a b d a c c b a d c b d a c a b d c a d b c d a b c d b a d b c a d b a c d c b a d c a b d a c b d a b c
// 输出全组合
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<vector> using namespace std; void recursive_combination(char* str, int num, vector<char> & result) // 从n个字符中取m个的组合 { if ( num == 0 ) { int length = result.size(); for ( int i = 0; i < length; i++ ) { cout << result[i]; } cout << endl; return; } if ( *str == '\0' ) { return; } result.push_back( *str ); // 取当前字符 recursive_combination( str+1, num-1, result ); result.pop_back(); // 不取当前字符 recursive_combination( str+1, num, result ); } void combination( char* str, int len ) { if ( str == NULL ) { return; } vector<char> result; for ( int i = 1; i <= len; i++ ) // 每一个组合长度 { recursive_combination(str, i, result); } } int main() { char str[] = {"abcd"}; int len = sizeof (str) / sizeof (char); cout << "src" << str << endl; cout << "output all combination: " << endl; combination(str, len); return 0; }
// main output as follow:
src: abcd output all combination: a b c d ab ac ad bc bd cd abc abd acd bcd abcd