Taking numbers as an example: there is an array of numbers A: 1 2 3 4, its full row by dictionary sequence column:
1 2 3 4
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 4 1
..........
N in total! Now input a number K and output its k-th Arrangement
Method: The idea of using Kanto code is actually to find the number at each position: the number at the first position, the number at the second position ....
Solution: calculate the number at each position in order. Here K = 8 is assumed; array: 1 2 3 4; Length: 4; position P indicates the number of P in the array: P = K/(n-1 )!
1. Calculate the number at the first position. P indicates the position of the first number in array.
1) P = 8/(4-1 )! = 8/6 = 1; ----------> the first number is a [1] = 2 2) Remove a [1] From array A, and the remaining number is 1 3 4 3) k = K % (4-1 )! = 8% 6 = 2
2. Repeat the process in step 1 to find the number at the second position:
1) At this time K = 2, array a becomes: 1 3 4, array length is 3 2) p = 1/(3-1 )! = 2/2 = 1; ----------> the second number is a [1] = 3 3) Remove a [1] From array A, and the remaining number is 1 4 4 4) k = K % (3-1 )! = 2% 2 = 0
3. Calculate the number at the 100th position and repeat the process of Step 1:
1) k = 0 at this time, and the loop ends. Before the end, we need to determine the number of remaining positions! In fact, it is very simple: no operation is required, that is, the remaining elements in array a are output in reverse order: At this time, the remaining numbers in array a are: 1, 4; so the third number in the result sequence is 4, number 4: 1
The condition for loop end is k = 0.
Final result: the 8th sequences are: 2 3 4 1
Code:
#include<iostream>#include<vector>#include<algorithm>using namespace std;int getNjiecheng(int n){ int res=1; for(int i=1;i<=n;i++){ res*=i; } return res;}vector<int> getPermutationSequence(int k,vector<int> v){ vector<int> res; int n=v.size(); if(k>getNjiecheng(n))return res; while(k>0){ int j=getNjiecheng(n-1); int p = k/j; k=k%j; if(k==0){ p-=1; res.push_back(v[p]); vector<int>::iterator iter=v.begin()+p; v.erase(iter); reverse(v.begin(),v.end()); for(int i=0;i<v.size();i++) res.push_back(v[i]); return res; } else{ res.push_back(v[p]); vector<int>::iterator iter=v.begin()+p; v.erase(iter); n--; } }}int main(){ vector<int> v; for(int i=1;i<=4;i++) v.push_back(i); vector<int> res=getPermutationSequence(24,v); for(vector<int>::iterator iter=res.begin();iter!=res.end();iter++){ cout<<*iter<<" "; } cout<<endl; return 0;}
If we want n! In full order: Just loop n! Call getpermutationsequence (25, V );
for(int i=1;i<=N!;i++){ getPermutationSequence(i,v);}
Evaluate the full arrangement of numbers or strings