zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):060-Permutation Sequence


    题目来源


    https://leetcode.com/problems/permutation-sequence/

    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.


    题意分析


    Input: n, k

    Output: the kth permutation in permutations based on n

    Conditions: 返回第n个排列


    题目思路


    看了网上答案发现还有这样一个方法,每一位都是nums[k/factorial],注意k要从0计数所以要减一,nums要及时移除已使用过的元素(不移除可以用False or True数组标记),factorial一般是n-1的阶乘,以上三个数都要更新


    AC代码(Python)


     1 class Solution(object):
     2     def getPermutation(self, n, k):
     3         """
     4         :type n: int
     5         :type k: int
     6         :rtype: str
     7         """
     8         res = ""
     9         
    10         nums = [i + 1 for i in xrange(n)]
    11         #count from 0
    12         k -= 1
    13         fac = 1
    14         for i in xrange(1, n):
    15             fac *= i
    16         for i in reversed(xrange(n)):
    17             index = k / fac
    18             value = nums[index]
    19             res += str(value)
    20             nums.remove(value)
    21             if i != 0:
    22                 k %= fac
    23                 fac /= i
    24         return res
  • 相关阅读:
    弹性盒子
    bzoj4237 稻草人
    bzoj2654 tree
    bzoj4813 [Cqoi2017]小Q的棋盘
    bzoj1014 [JSOI2008]火星人
    bzoj3242 [Noi2013]快餐店
    bzoj4025 二分图
    bzoj3237 [Ahoi2013]连通图
    bzoj3244 [Noi2013]树的计数
    bzoj2431 [HAOI2009]逆序对数列
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5088253.html
Copyright © 2011-2022 走看看