LeetCode Permutation Sequence

Source: Internet
Author: User

LeetCode Permutation Sequence
Permutation Sequence for LeetCode solving

Original question

Find [1, 2, 3... N] is the largest k in the sequence composed of all numbers.

Note:

N is a number ranging from 1 to 9.

Example:

Input: n = 3, k = 3
Output: "213"

Solutions

Because n different numbers can constitute n! Then the first sequence is (n-1 )! Different possibilities, and these sequences are grouped according to the first size, 1... Is the smallest (n-1 )! , 2... Yes (n-1 )! + 1 to 2 (n-1 )! Now you only need to calculate the number of k (n-1 )! You can determine the first digit. You can also use this method to determine the second and third digits ...... In addition, since the subscript of the list starts from 0, k must be subtracted from 1.

AC Source Code
class Solution(object):    def getPermutation(self, n, k):        """        :type n: int        :type k: int        :rtype: str        """        k -= 1        factorial = 1        for i in range(1, n):            factorial *= i        result = []        array = list(range(1, n + 1))        for i in range(n - 1, 0, -1):            index = k // factorial            result.append(str(array[index]))            array = array[:index] + array[index + 1:]            k %= factorial            factorial //= i        result.append(str(array[0]))        return "".join(result)if __name__ == "__main__":    assert Solution().getPermutation(3, 3) == "213"    assert Solution().getPermutation(9, 324) == "123685974"

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.