LeetCode:Permutation Sequence
2015-06-12 12:24
465 查看
problems:
The set
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
思路: 采用的是康托编码的逆向展开算法。
由于我们是从0开始计数,k -= 1;(k-1)
首先,初始化一个vecotr,nums中的元素依次为:1, 2, 3;
获取第一位数字:k / 2! = 1,第一个数字就是 2,同时,从vector中删除已经使用的元素,剩余数字:1,3,并且k = k % 2! = 0;
获取第二个数字:k / 1! = 0,第二个数字就是1,同时,从链表中删除已经使用的元素),vector剩余数字:3,
由于达到最后一位,不需要操作k了。 获取第三个(最后)数字:剩余元素3
最终三个数字为213。
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.
思路: 采用的是康托编码的逆向展开算法。
由于我们是从0开始计数,k -= 1;(k-1)
首先,初始化一个vecotr,nums中的元素依次为:1, 2, 3;
获取第一位数字:k / 2! = 1,第一个数字就是 2,同时,从vector中删除已经使用的元素,剩余数字:1,3,并且k = k % 2! = 0;
获取第二个数字:k / 1! = 0,第二个数字就是1,同时,从链表中删除已经使用的元素),vector剩余数字:3,
由于达到最后一位,不需要操作k了。 获取第三个(最后)数字:剩余元素3
最终三个数字为213。
class Solution { public: string getPermutation(int n, int k) { vector<int> nums; vector<int> factors; //初始化为一个元素,初始化为1 for(int i=0;i<n;i++) { nums.push_back(i+1); if(!i) factors.push_back(1); else factors.push_back(factors[i-1]*i); } string result; int position; for(int i=n-1;i>-1;i--) { position=(k-1)/factors[i]; k = k - position * factors[i]; result.push_back(nums[position]+48); //其实最后一位可以不用操做k nums.erase(nums.begin()+position); } return result; } };
相关文章推荐
- 由@DynamicInsert(true) @DynamicUpdate(true)引发的“血案”
- UGUI 学习笔记
- 解决maven的“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- 优化后的快速模糊查询插件QuickQuery
- LeetCode62:Unique Paths
- Android UI优化工具的使用 HierchyViewer
- UIImageView只显示一半
- quick3x_游戏场景计时器
- Android UI自动化测试最佳实践
- UA 4255 Guess (拓扑排序)
- RequireJS 2.0初探
- 在无法判断ANSI还是UICODE编码方式下的字符函数的使用
- RequireJS学习笔记
- 关于音响系统参数测试的主要参数之二: Frequency Response(频率响应范围)
- UIView的layoutSubviews和drawRect
- 百度UEditor添加视频 增加支持“通用代码”功能,支持微信
- iOS运动视觉效果-UIMotionEffect
- 给UILabel 或者 UIButton标题加下划线
- Solve workmate's issue
- Android UI自动化测试最佳实践