[Leetcode] permutation sequence

Source: Internet
Author: User

The set [1, 2, 3 ,...,N] Contains a totalN! Unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie,N= 3 ):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

GivenNAndK, ReturnKTh permutation sequence.

Https://oj.leetcode.com/problems/permutation-sequence/

Computing 1 ~ K of N numbers

Idea 1: Count from small to large until the K. It must be time-out ..

Idea 2: Calculate the k-th order based on the rule.

Analysis: 1 ~ N total N! (N-1 )! , Starting with 2 (n-1 )! (N-1) at the beginning of... n )! . Therefore, K/(n-1) is used )! The first number is determined, and the number is removed in turn (n-1 )! K % (n-1) in the number )! Number.

Idea 2 code:

 

public class Solution {    public String getPermutation(int n, int k) {        int[] num = new int[n];        int permSum = 1;        for (int i = 0; i < n; i++) {            num[i] = i + 1;            permSum *= (i + 1);        }        StringBuilder sb = new StringBuilder();        k--;//change to base 0        for (int i = 0; i < n; i++) {            permSum = permSum / (n - i);            int selected = k / permSum;            sb.append(num[selected]);            for (int j = selected; j < n - i - 1; j++)                num[j] = num[j + 1];            k = k % permSum;        }        return sb.toString();    }    public static void main(String[] args) {        System.out.println(new Solution().getPermutation(4, 10));    }}

 

Refer:

Http://blog.csdn.net/havenoidea/article/details/12837441

Http://www.cnblogs.com/TenosDoIt/p/3721918.html

 

 

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.