- Title: https://leetcode.com/problems/permutation-sequence/
- Analysis: Cantor Code
- Code
//Leetcode, permutation Sequence//Cantor code, TIME complexity O (n), Space complexity O (1)classsolution{ Public: stringGetpermutation (intNintk) {stringS (N,'0'); stringresult; for(inti =0; I < n; ++i) s[i]+ = i +1; returnKth_permutation (s, k); }Private: intFactorial (intN) {intresult =1; for(inti =1; I <= N; ++i) Result*=i; returnresult; }//seq has been sequenced and is the first permutationTemplate<typename sequence>Sequence kth_permutation (ConstSequence &seq,intk) {Const intn =seq.size (); Sequence S (seq); Sequence result; int Base= Factorial (N-1); --k;//Cantor code starting from 0 for(inti = n-1; i >0; K%=Base,Base/= I,---i) {Auto a= Next (S.begin (), K/Base); Result.push_back (*a); S.erase (a); } result.push_back (s[0]);//last one returnresult; }};
Reference: Https://github.com/soulmachine/leetcode
[Leetcode] Permutation Sequence