I forgot to write the next arrangement in STL.
It takes more than one hour to write data. If recursive writing is used, the error will be saved in a list, and then K/(n-1) will be used )! The factorial is the number to be deleted, but after observation,
For example, list = {1, 2, 3}
Divided into three groups:
1 {2, 3}
2 {1, 3}
3 {1, 2}
Determine the group in which nyoj 511 is located, and then determine the number of nyoj in which group.
Find 3rd permutation, 3% 2 = 1, delete list is 3rd number 3, in fact it is 2nd tree 2, so the calculation method is (k-1)/(n-1 )!
For the next group, K % (n-1 )! No. 4th, 4%! = 0. It should actually be the second 2.
This idea is similar to nyoj's ball fall (nyoj 511)
1 public class Solution { 2 3 private String ans=""; 4 public int calu(int n) 5 { 6 if(n==0) return 1; 7 int sum=1; 8 for(int i=2;i<=n;i++) 9 {10 sum*=i;11 }12 return sum;13 }14 15 public String getPermutation(int n, int k) {16 ArrayList<Integer> arry=new ArrayList<Integer>();17 for(int i=1;i<=n;i++)18 {19 arry.add(i);20 }21 22 get(k,calu(n-1),arry);23 return ans;24 25 }26 public void get(int k,int n1,ArrayList<Integer> list)27 {28 if(list.size()==1)29 {30 ans+=list.remove(0);31 return;32 }33 int a=list.remove((k-1)/n1);34 ans+=a;35 int te=k%n1;36 if(te==0) te=n1;37 get(te,n1/list.size(),list);38 39 40 }41 }
View code