Leetcode: Permutation Sequence
2015-09-09 08:50
507 查看
Question
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):
“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive
Solution
[code]class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ if n<=0 or k<0: return '' res = [] k -= 1 factorial = 1 for ind in range(2,n): factorial *= ind nums = range(1,n+1) round = n-1 while round>=0: index = k/factorial k %= factorial res.append(nums[index]) del nums[index] if round>0: factorial /= round round -= 1 res = [str(elem) for elem in res] res = ''.join(res) return res
The thing I need to notice is that k should be decreased by 1 first.
相关文章推荐
- sql_question
- PHP中关于break与continue的使用
- EasyUI Tabs
- BinaryTreePath
- Leetcode Implement Queue using Stacks
- iOS8 自定义UITabBar (使用popToViewController导致的UITabBarButton重叠的问题)
- Leetcode Implement Stack using Queues
- Android Call requires API level 11 (current min is 8)的解决方案
- Implement stack using a queue
- LCT - hdu4010 Query on The Trees
- UVA11572_Unique Snowflakes
- UVA1152_4 Values whose Sum is 0
- 块设备驱动程序中request方式和make_request方式的区别(阅读笔记)
- UIPageViewController bug
- N-Queens LeetCode OJ
- build wireshark on windows
- Google Guice使用入门
- easyui小技巧
- leetcode Unique Binary search Trees
- java 图形界面 gui