The Set[1,2,3,…,n]Contains a total of n! Unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3 ):
"123"
"132"
"213"
"231"
"312"
"321"
Given N and K, return the kth permutation sequence.
Note: given n will be between 1 and 9 inclusive.
# If 0 class solution {public: STD: String getpermutation (int n, int K) {STD: String s; For (INT I = 0; I <N; I ++) {S. push_back (I + 1 + '0');} int CNT = 0; do {CNT ++;} while (STD: next_permutation (S. begin (), S. end () & CNT <k); # If 0std: cout <S <STD: Endl; # endif // 1 return s ;}}; # endif // The Code TLE. (general solution) # If 1 class solution {public: STD: String getpermutation (int n, int K) {STD: vector <int> VEC (n, 0 ); int T = 1; for (INT I = 0; I <n; I ++) {VEC [I] = I + 1; T * = I + 1;} STD:: String s; k --; For (INT I = 0; I <n; I ++) {T/= n-I; S. push_back (VEC [k/T] + '0'); Vec. erase (VEC. begin () + k/T); K % = T ;}# if 0std: cout <S <STD: Endl; # endif // 1 return s ;};# endif // 1
Leetcode-permutation sequence