【LeetCode】Permutation Sequence
来源:互联网 发布:表情包 知乎 编辑:程序博客网 时间:2024/04/29 12:09
题目描述:
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.
总觉的这题目我的思路有点绕……若以“1234……n”为第一个序列,那么一个序列的序号是由尾部变动的位数来决定的,以n=4为例,第一个序列为“1234”,只变动最后一位,则最多到1!,变动倒数第二位,则最多到2!=2,倒数第三位则变动到3!=6号序列,由此我们可以将前面顺序部分的个数求出来。下一步就是确定后面每一位的数字。对倒数第i位,令m = k / i!,s="1234",则swap( s[n-i], n-i+1+m ),为了保持交换后序列还是按升序排列的,我们将它依次换过去,则m+1次交换。
还是以1234为例:
0 1 2 3
1、1 2 3 4
2、1 2 4 3
3、1 3 2 4
4、1 3 4 2
5、1 4 2 3
6、1 4 3 2
当k=3时,通过前面第一步我们可以确定第一位是不需要改变的(初始序列为“1234”),然后就该确定s[1]位置的数字,此时i=3,则s[1]的数字每经过(i - 1)!个序列变化一次。令m = k / (i - 1)!=3 / 2 = 1,则s[1]与s[1 + m]=s[2]交换,得到1324,k -= m * (i-1)! =1>=1,则循环终止,否则将k减掉后继续循环。
代码如下:
class Solution {public:string getPermutation(int n, int k) {string ret;for (int i = 1; i <= n; i++)ret += i + '0';int i(0), mult(1);while (mult < k){i++;mult *= i;}if (i)mult /= i;while (k>1){for (int j = 0; j < (k - 1) / mult; j++)swap(ret[n - i], ret[n - i + 1 + j]);k -= (k - 1) / mult*mult;mult /= --i;}return ret;}};
0 0
- LeetCode: Permutation Sequence
- LeetCode Permutation Sequence
- [Leetcode] Permutation Sequence
- [LeetCode] Permutation Sequence
- leetcode 74: Permutation Sequence
- leetcode Permutation Sequence
- [leetcode] Permutation Sequence
- [LeetCode]Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode-Permutation SequencePermutation Sequence
- [leetcode] Permutation Sequence
- LeetCode - Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode 60: Permutation Sequence
- Leetcode: Permutation Sequence
- leetcode Permutation Sequence
- LeetCode | Permutation Sequence
- LeetCode Permutation Sequence
- 选择屏幕动态显示title
- without application to…
- 五招吃烧烤不易致癌
- 关于svn的搭建
- Android开源项目 [分类 便于查看]
- 【LeetCode】Permutation Sequence
- JavaScript-4.6鼠标事件监听,获取鼠标坐标window.event---ShinePans
- CtreeCtrl加载图标的两种方式
- 读懂心态
- 解决subclipse同步冲突问题A conflict in the working copy obstructs the current operation
- Android Bundle传递简单数据、对象数据
- SSL/TLS协议运行机制的概述
- Unity3D中实现动态加载Resources目录外的资源
- Linux内核源码分析--内核启动命令行的传递过程(Linux-3.0 ARMv7)