Leetcode permutation Sequence-----java

Source: Internet
Author: User

The set [1,2,3,…,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.

Note:given N would be between 1 and 9 inclusive.

The problem is to give a number n and a number k, and then output the K in a permutation combination of all the numbers of 1-n. The rules are as follows (first change the number behind, that is, four numbers, the first is 1234, the second is 1243)

Then it is easier to think clearly about the problem.

There are a total of n numbers, then each number starts with (n-1)! species, that is, if 1<=k<= (n-1)! Then this combination will start with 1.

After the first number has been determined, then the following number is determined in the same way, on the basis of the first number, with a number (n-2)! species, so it can be inferred that:

  When you ask for the K string, the number is determined from the front to the back, and count refers to the number of combinations that begin with a number in the current number.

 Public classSolution { PublicString Getpermutation (intNintk) {int[] flag =New int[n];        String result; Char[] ans =New Char[n]; intCount = 1;  for(inti = 2;i<n;i++) Count*=i;  for(inti = 0;i<n;i++){            if(k = = 1){                 for(intj = 0;j<n;j++){                    if(Flag[j] = = 0) {Ans[i]= (Char) (j+49); I++; FLAG[J]= 1; }                }                return NewString (ans); }            intnum = (k-1)/count; K= k-num*count; Count= count/(n-1-i);  for(intj = 0;j<n;j++){                if(Flag[j] = = 0){                    if(num = = 0) {Ans[i]= (Char) (j+49); FLAG[J]= 1;  Break; }ElseNum--; }            }        }        return NewString (ans); }}

This problem is a rare time to submit the fastest.

Leetcode permutation Sequence-----java

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.