leetcode60. Permutation Sequence
2016-07-10 17:34
295 查看
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”
思路:空间二分法(轻拍,我瞎bb的)
将[1,2,3,…n]储存在数组中,下标对应0,1,…n-1
每一个数作为字符串打头,则后面的组合有(n-1)!种
二分法来定位,当定位到a[x](len(a)-1)!<=t
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”
思路:空间二分法(轻拍,我瞎bb的)
将[1,2,3,…n]储存在数组中,下标对应0,1,…n-1
每一个数作为字符串打头,则后面的组合有(n-1)!种
二分法来定位,当定位到a[x](len(a)-1)!<=t
class Solution(object): def back(self,a,t,s): if len(a)==1: return s+str(a[0]) start=0;end=len(a)-1 x=len(a)-1;quad=1 while(x): quad=quad*x x=x-1 while(True): mid=(end-start)/2+start tmp=mid*quad if end-start>1: if tmp<(t-1): start=mid elif tmp>(t-1): end=mid else: s=s+str(a[mid]) a.remove(a[mid]) for i in a: s=s+str(i) return s else: flag=start tmp=start*quad if end*quad<=(t-1): flag=end tmp=end*quad s=s+str(a[flag]) a.remove(a[flag]) s=self.back(a,(t)-tmp,s) return s def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ s='' a=[i for i in range(1,n+1)] t=k s=self.back(a,t,s) return s
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解