Leetcode--60. Permutation Sequence
来源:互联网 发布:站点数据和格点数据 编辑:程序博客网 时间:2024/06/05 14:56
题目
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.
思路
假设集合为[1,2,3,4],求出第6个组合。
第6个组合对应的下标为5(下标从0开始),我们首先求出5所对应的lehmer码(lehmer code的解释参考链接1):
5/3! = 0 余5
5/2! = 2 余1
1/1! = 1 余0
0 (lehmer code最后一位总为0)
所以所求lehmer码为0210
当前集合对应的序列为1234
接下来将lehmer码中的每个数字当做当前序列的下标,下标0对应的集合元素为1,当前序列变成234;下标2对应的集合元素为4,当前序列变成23;下标1对应的集合元素为3,当前序列变成2;下标0对应的元素为2
所以所求的组合即为1432
代码
class Solution {public: string getPermutation(int n, int k) { vector<int> jc; ///阶乘表 list<int> li; ///序列 1234 jc.push_back(1); int i=1; for(; i<n; i++) { jc.push_back(jc[i-1]*i); li.push_back(i); } li.push_back(i); --k; string res=""; list<int>::iterator it; for(int i=n-1; i>0; i--) { int index = k/jc[i]; it = li.begin(); for(int j=0; j<index; j++) it++; res += to_string(*it); li.erase(it); k = k % jc[i]; } res += to_string(*li.begin()); return res; }};
阅读全文
0 0
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode:60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60. Permutation Sequence
- [LeetCode] 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- Leetcode-60. Permutation Sequence
- [LeetCode]--60. Permutation Sequence
- leetcode-60. Permutation Sequence
- Javascript手把手教你做商品放大镜效果
- C#网络编程(基本概念和操作)
- Centos7 vnc断电后黑屏问题解决方案
- java去除两个数组中相同的元素
- sphinx4的数据处理器的构建
- Leetcode--60. Permutation Sequence
- UAP开发(NC63)遇到的错误记录
- 最强PostMan使用教程(1)
- POJ 3304 Segments(在直线上投影有公共点,直线和线段交)
- mysql 查看当前使用的配置文件my.cnf的方法
- zt storm的ack与fail
- foolbox:一款神奇的Python工具箱
- html中的一些学习
- 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”