LeetCode 60. Permutation Sequence
2016-05-15 17:00
387 查看
题目
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.
求解过程:
①本题自己首先考虑采用STL中的next_permutation(),结果果断超时,看来题目考察的不是这个方法;
②然后,自己又把这个方法next_permutation()具体实现了一遍,结果还是超时;
③后面,看了一篇博客文章,上面采用的这用方法:
给了我们n还有k,在数列 1,2,3,… , n构建的全排列中,返回第k个排列。
题目告诉我们:对于n个数可以有n!种排列;那么n-1个数就有(n-1)!种排列。
那么对于n位数来说,如果除去最高位不看,后面的n-1位就有 (n-1)!种排列。
所以,还是对于n位数来说,每一个不同的最高位数,后面可以拼接(n-1)!种排列。
所以你就可以看成是按照每组(n-1)!个这样分组。
利用 k/(n-1)! 可以取得最高位在数列中的index。这样第k个排列的最高位就能从数列中的index位取得,此时还要把这个数从数列中删除。
然后,新的k就可以有k%(n-1)!获得。循环n次即可。
同时,为了可以跟数组坐标对其,令k先–。
重点内容 cpp
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.
求解过程:
①本题自己首先考虑采用STL中的next_permutation(),结果果断超时,看来题目考察的不是这个方法;
②然后,自己又把这个方法next_permutation()具体实现了一遍,结果还是超时;
③后面,看了一篇博客文章,上面采用的这用方法:
给了我们n还有k,在数列 1,2,3,… , n构建的全排列中,返回第k个排列。
题目告诉我们:对于n个数可以有n!种排列;那么n-1个数就有(n-1)!种排列。
那么对于n位数来说,如果除去最高位不看,后面的n-1位就有 (n-1)!种排列。
所以,还是对于n位数来说,每一个不同的最高位数,后面可以拼接(n-1)!种排列。
所以你就可以看成是按照每组(n-1)!个这样分组。
利用 k/(n-1)! 可以取得最高位在数列中的index。这样第k个排列的最高位就能从数列中的index位取得,此时还要把这个数从数列中删除。
然后,新的k就可以有k%(n-1)!获得。循环n次即可。
同时,为了可以跟数组坐标对其,令k先–。
重点内容 cpp
class Solution { public: string getPermutation(int n, int k) { if(n==1) { return "1"; } vector<int> vec; for(int i = 1;i<=n;i++) { vec.push_back(i); } k--; vector<int> factorial(n,1); for(int i = 1;i < n;i++) { factorial[i]= factorial[i-1]*i; } string s=""; for(int i = n;i >=1;i--) { int index = k/factorial[i-1]; char c = (char)(vec[index]+'0'); s+=c; vec.erase(vec.begin()+index); k %= factorial[i-1]; } 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 题解