求一个全排列函数:
如p([1,2,3])输出:
[123]、[132]、[213]、[231]、[321]、[312]
def permutations(n): indices = list(range(n)) yield indices while True: low_idx = n - 1 while low_idx > 0 and indices[low_idx-1] > indices[low_idx]: low_idx -= 1 if low_idx == 0: break # 排列中最后一个升序的首位 low_idx -= 1 high_idx = low_idx + 1 # 找到最后一个比low_idx 对应大的最后一个数 while high_idx < n and indices[high_idx] > indices[low_idx]: high_idx += 1 high_idx -= 1 indices[low_idx], indices[high_idx] = indices[high_idx], indices[low_idx] indices[low_idx+1:] = reversed(indices[low_idx+1:]) yield indices
//思路:拿数组的第一个字符和后面所有字符交换,递归地把后面的字符当作一个新的数组,再次把第一个字符和后面所有字符交换,直到新数组里只有一个元素,打印出字符串。 #include <iostream> using namespace std; #define N 5 void Print(int* arr, int length); void swap(int &a, int &b); void perm(int* arr, int* ptr, int length) { if (length == 1) { Print(arr, N); return; } for (int i = 0; i < length; ++i) { swap(ptr[0], ptr[i]); perm(arr, ptr+1, length-1); swap(ptr[0], ptr[i]); } } void Print(int* arr, int length) { for (int i = 0; i < length; ++i) { printf("%d ", arr[i]); } cout << endl; } void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
方法1:依次从字符串中取出一个字符作为最终排列的第一个字符,对剩余字符组成的字符串生成全排列,最终结果为取出的字符和剩余子串全排列的组合。