# Leetcode -- Permutation Sequence

Source: Internet
Author: User

Leetcode -- Permutation Sequence

Problem Description:

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 will be between 1 and 9 inclusive.

Analysis:

The first thought of the violence law is arranged one by one until the k Order is found. After the submission, it will time out. After searching online, we can find that we can directly construct the k arrangement, take n = 4, k = 17 as an example. The array src = [1, 2, 3 ,..., n].

What is the first number of 17th orders? We know the number of orders starting with a fixed number = (n-1 )! = 3! = 6, that is, a total of 6*2 = 12, 12 <17, so the first number of 17th orders cannot be 1 or * 3> 17, therefore, the first number of 17th orders is 3. That is, the first number of 17th arrays is the number of m = upper (17/6) = 3 (upper indicates an ascending integer) of the original array (ascending order of the original array.

After the first number is fixed, we delete the number from the src array, which is equivalent to finding the k-(m-1) * (n-1) based on the current src )! = 17-2*6 = 5 arrays, so this problem can be solved recursively.

In code implementation, pay attention to a small detail, that is, starting from k -- to make the subscript start from 0. In this way, the subscript is from 0 to n-1, so we do not need to consider n to get the remainder, better match with the array subscript. The Code is as follows:

```Class Solution {public: int fun (int n) {if (n <0) return 0; else if (n = 0) return 1; elsereturn n * fun (n-1);} string getPermutation (int n, int k) {string s; int total = fun (n); if (total

Flag (n, 0); // because the array is from 0 to n-1, so the base from 0 to K-1 -- k; for (int I = 0; I

```
Related Keywords:

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.