Leetcode sorting: k-th sorting

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.