60. Permutation Sequence
来源:互联网 发布:计算圆周率的算法 编辑:程序博客网 时间:2024/05/16 16:59
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.
题意:给出数字n,计算n的全排列中第k个排列。
思路:计算,说明这是可以计算的,以1-9为例,以字母1开头的排列的个数是(n-1)!个,那么如果k里包含2个(n-1)!,但是小于3个(n-1)!呢,则这第k个排列一定是以3开头的,同理后边的数字也是这么推的。
class Solution {public:string getPermutation(int n, int k) {vector<int> dp(n+1, 1);for (int i = 2; i <= n; i++){dp[i] = dp[i - 1] * i;}//record n!vector<int> nums(n, 1);for (int i = 0; i < n; i++)nums[i] = i + 1;k = (k-1)%dp[n];string s(n,'1');for (int i = 0; i < n; i++){int index = k / dp[n - 1 - i];s[i] = nums[index] + '0';nums.erase(nums.begin() + index);k %= dp[n - 1 - i];}return s;}};
0 0
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- hiho 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 菜鸟的第一篇C博:希望成长
- ORA-01157 错误解决,原因DBWR锁定产生
- HDU 2571
- 如何解决Tomcat启动时重复出现Socket accept failed错误
- Android打造ListView万能适配器
- 60. Permutation Sequence
- Block如何避免self retain
- LINUX 新增的磁盘不建立分区,直接建立文件系统并挂载怎么办?
- centos6.5配置静态ip
- 封装类似jQuery的ajax函数
- android studio创建assets目录并且利用webView加载其html(by 星空武哥)
- LeetCode 72. Edit Distance(编辑距离)
- [leetcode]【数组】81. Search in Rotated Sorted Array II
- SciTe 中文设置(解决乱码,中文界面)