Source: Internet
Author: User

Label:

One Day Together Leetcode series (i) Title(ii) The first solution to solve the problem:The set [,..., 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):

1: "123"

2: "132"

? 3: "213"

4: "231"

5: "312"

6: "321"

Given N and K, return the kth permutation sequence.

Reference: "One day together Leetcode" #31. Next permutation this blog, very strange is why n=8,k=8590 time will time out, for the moment has not thought out the reason, welcome the message discussion.

`/ * Use STL next_permutation to find the next number of permutations at a time * /classSolution { Public:stringGetpermutation (intNintK) {stringSeqstringRet for(inti =0; I < n; i++) {seq+= (' 1 '+ i); } Do{k--;if(k==0) {ret = seq; Break; } } while(Next_permutation (Seq.begin (), Seq.end ()));returnRet }};`

The second method of solution:
The law of permutation number is used to solve.

Let's take the example given in the topic to explain the law. N=3, consisting of three-by-four-digit {A1,A2,A3}

1: "123"

2: "132"

3: "213"

4: "231"

5: "312"

6: "321"

First the first number A1 (Candidate temp = "123"), K is 1, 2 o'clock, A1=1,k is 3, 4 o'clock, A1=2,k is 5, 6 o'clock, a1=3, from which you can see a1=temp[(k-1)/(N-1)!].

After determining the first number we look at the second number A2, in order to see this group, ruled out 1, candidate number temp = "23", this time K can only be 1 and 2, so in the previous step k%= (n-1)!, this time a2=temp[(k-1)/(N-2)!

The last A3 can only be for the remaining number.

OK, to tidy up the idea, we need a candidate string temp, one (n-1)! Array F[10] = {1,1,2,6,24,120,720,5040,5040*8} (n is 1~9 number), K initial value is K-1

In each step, a1=temp[k/f[n-1]],k%=f[n-1]. Until n is 0.

See the code for specific ideas:

`classSolution { Public:stringGetpermutation (intNintK) {stringtemp ="123456789";intF[] = {1,1,2,6, -, -,720,5040,5040*8};stringRetinti = n; k--;initial value of//k while(i) {intm = k/f[i-1]; K%=f[i-1]; RET+=TEMP[M]; Temp.erase (Temp.begin () +m);//Erase values that have already been selectedi--; }returnRet }};`

"One Day together Leetcode" #60. Permutation Sequence.