leetcode4:Permutation
#include <utility> #include <iostream> #include <vector> #include <algorithm> //the next permutation template<class BidirIt> bool STL_next_permutation(BidirIt first, BidirIt last) { if (first == last) return false; BidirIt i = last; if (first == --i) return false; while (1) { BidirIt i1, i2; i1 = i; --i; if (*i < *i1) { i2 = last; while (!(*i < *--i2)) ; std::iter_swap(i, i2); std::reverse(i1, last); return true; } if (i == first) { std::reverse(first, last); return false; } } } void nextPermutation(int A[],int len) { STL_next_permutation(A, A+len); } //full pemutation void fullPerm(int A[],int m,int n) { if(m == n) { for(int i=0;i<n+1;i++) std::cout << A[i] << " "; std::cout << std::endl; return; } else { for(int i=m;i<n+1;i++) { std::swap(A[m], A[i]); fullPerm(A,m+1,n); std::swap(A[m], A[i]); } } } int Factorial(int n) { int fac=1; for(int i=1;i<=n;i++) { fac *=i; } return fac; } //康托编码第k个序列 void CantorCode(int A[],int len,int k) { --k; std::vector<std::pair<int,bool>> v; for(int i=0;i<len;i++) { v.emplace_back(A[i],false); } for(int i=0;i<len;i++) { int j; int t=k/Factorial(len-i-1); for(j=0;j<len;j++) { if(!v[j].second) { if(t==0) break; --t; } } A[i]=v[j].first; v[j].second=true; k=k%Factorial(len-i-1); } }