Original title Address
A simulation must be timed out, only the birth of the law to find out.
For example n=4,k=10, first write out all the permutations of the n=4:
(1) 1 2 3 4 (2) 1 2 4 3 (3) 1 3 2 4 (4) 1 3 4 2 (5) 1 4 2 3 (6) 1 4 3 2 (7) 2 1 3 4 (8) 2 1 4 3 (9)
2 3 4 1 <--target sequence (11) 2 4 1 3 (12) 2 4 3 1 (13) 3 1 2 4 (14) 3 1 4 2 (15) 3 2 1 4 ... (Omit the following)
Assuming the end result is ABCD
First determine A. Because k=10 > 3!=6, I can figure out that a should be 1~n ceiling{k/3!} = 2 (ceiling means take up the whole), i.e. a=2. Finally remove 2 from 1~n, update K, make k=k%3!=4
Then determine B. Because k=4 > 2!=2, I can figure out that B should be 1~n ceiling{k/2!} = 2, because 2 was deleted before, so now the 2nd number is 3, namely b=3. Finally remove 3 from 1~n, update k=k%2!=2
Then look at c. Because k=0, the sequence we asked for is definitely at the end of a sequence, so the numbers followed are output from large to small, i.e. c=4. Remove 4 from 1~n and continue.
finally see D. Because K=0, ibid, can get d=1.
(write some abstract, later have time to re-processing it ...) )
Code:
1 stringGetpermutation (intNintk) {2 stringRes (n,0);3vector<Char> Avail (n,0);4 intp =1;5 for(inti =1; I <= N; i++) {6P *=i;7Avail[i-1] = i +'0';8 }9 Ten for(inti =0; I < n; i++) { One if(k >0) { A intNEXTP = P/(N-i); - intOrder = (K-1) /nextp; -Res[i] =Avail[order]; theAvail.erase (Avail.begin () +order); -K%=nextp; -p =nextp; - } + Else { -Res[i] =Avail.back (); + Avail.pop_back (); A } at } - - returnRes; -}
leetcode#60 permutation Sequence