Leetcode 60.Permutation Sequence (permutation sequence) thinking and method of solving problems

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.

Idea: This problem is still relatively difficult, violence is to find dead, time-out did not gave. But the method of mathematical induction is not everyone can think, read a lot of information, also just understand some ideas.

Law: Known n values, learned permutations and combinations know a common n! Species arrangement.
The first sequence with each number starts with (N-1)! sequence, so n numbers so there's a n! A sequence.
And so on, the second digit starts with every number (N-2)! A sequence.

The specific code is as follows:

public class Solution {    String str = "";    Public String getpermutation (int n, int k) {    int[] num = new Int[n];        int[] data = new int[n];//the dataset of the factorial,        int i = 0;        for (; i < n; i++) {        num[i] = i+1;        if (i = = 0)        data[i] = 1;        else{        Data[i] = data[i-1]*i;        }        }        k--;        while (---->-1) {//loop get the numbers        int k1 = k/data[i];        int p = k1+ (n-1-i);//Digital position        swap (n-1-i,p,num);        if (k = k%data[i]) = = 0)//k==0 end break        ;        }        for (int x:num)//Get str        str + = x;        return str;    }    Insert the data, followed by the public    Void swap (int i,int j,int[] num)    {    int m = num[j];        for (int k=j;k>i;k--)        num[k]=num[k-1];        num[i]=m;}    }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 60.Permutation Sequence (permutation sequence) thinking and method of solving problems

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.