标签:
递归算法:n个元素的全排列=n x (n-1)个元素的全排列。
非递归算法:求一个排列的下一个字典序排列,stl已经有的next_permutation()函数。
#include <iostream> #include <algorithm> using namespace std; int main(){ int arr[4]={1,2,3,4}; do{ for(int i = 0; i < 4; i++){ cout << arr[i] << ‘ ‘; } cout << endl; }while(next_permutation(arr,arr+4)); cout << "final state:" <<endl; for(int i = 0; i < 4; i++){ cout << arr[i] << ‘ ‘; } cout << endl; return 0; }
#include <iostream> using namespace std; template <class T> void Swap(T &a,T &b){ T temp = a; a = b; b = temp; } template <class T> void Swap(T list[],int i,int k){ T list_i = list[i]; if(i < k){ for(int j = i; j < k; j++){ list[j]= list[j+1]; } } else if(i > k){ for(int j = i; j>k; j--){ list[j]= list [j-1]; } } list[k] = list_i; } template <class T> void Perm(T list[],int k,int m){ if(k == m){ for(int i = 0; i <= m; i++){ cout << list[i] << ‘ ‘; } cout << endl; } else{ for(int i = k; i <= m; i++){ Swap(list, i, k); Perm(list, k+1, m); Swap(list, k, i); } } return; } int main(){ int a[6]={1,2,3,4,5,6}; Perm(a,0,3); return 0; }
#include <iostream> using namespace std; template <class T> void Swap(T &a,T &b){ T temp = a; a = b; b = temp; } template <class T> void Reverse(T list[], int i, int k){ //转置 T *listcpy = new T[k + 1]; for(int j = i; j <= k; j++){ listcpy[j] = list[i + k - j]; } for(int j = i; j <= k; j++){ list[j] = listcpy[j]; } delete listcpy; } template <class T> int Upper_Bound(T list[], int l, int r, T item){ //二分查找降序序列(l,r)中 int mid = (l + r + 1) / 2; //第一个大于item的位置 while(l < r){ mid = (l + r + 1) / 2; if(list[mid] < item){ r = mid - 1; } else{ l = mid; } } return l; } template <class T> bool Next_Permutation(T list[], int i, int k){ int n = -1, m = 0, t = k; while(n == -1 && t != i){ if(list[t] > list[t-1]){ //n的位置 n = t - 1; } t--; } if(n == -1){ //降序 Reverse(list, i, k); return false; } else{ m = Upper_Bound(list, n+1, k, list[n]); //m的位置 Swap(list[n], list[m]); //交换n,m上的值 Reverse(list, n+1, k); //倒置从n+1到k return true; } } int main(){ int arr[4]={1,2,3,4}; do{ for(int i = 0; i < 4; i++){ cout << arr[i] << ‘ ‘; } cout << endl; }while(Next_Permutation(arr, 0, 3)); cout << "final state:" <<endl; for(int i = 0; i < 4; i++){ cout << arr[i] << ‘ ‘; } cout << endl; return 0; }
讲道理非递归效率应该比递归要高……
标签:
原文地址:http://www.cnblogs.com/shuiming/p/5922440.html