【LeetCode】60. Permutation Sequence
2016-03-22 10:41
441 查看
题目:
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.
提示:
这道题我一上来使用了backtracking的方法依次构造出排列数,当然结果不出所料的TLE了。实际上,仔细观察这些数字,我们还是不难发现一些规律的。
假设有四位数字{1, 2, 3, 4},那么他们能够产生的排列数是什么呢?
1 + {2, 3, 4}
2 + {1, 3, 4}
3 + {1, 2, 4}
4 + {1, 2, 3}
其实就是选定第一位数字后,其他剩下的数字进行排列组合,就能求出以该数字打头的所有排列组合。想必已经能发现一些规律了,我们干脆再举一个具体的例子,比如我们现在想要找第14个数,那么由于14 = 6 + 6 + 2。因此第一个数打头的是3,然后再求{1, 2, 4}中第二个排列组合数,答案是"142"。所以最终答案就是"3142"啦。
这里有一些问题是需要我们注意的:
构造排列数从最高位开始,当选出一个数字后,就应当把这个数字erase掉,防止后面又出现;
我们所要求的第k个数需要在每次循环中减去对应的值;
注意程序中的数组是从0开始的,但题目的输入是从1开始计数的。
代码:
class Solution { public: string getPermutation(int n, int k) { vector<int> permutation(n + 1, 1); for (int i = 1; i <= n; ++i) { permutation[i] = permutation[i - 1] * i; } vector<char> digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; int num = n - 1; string res; while (num) { int t = (k - 1) / (permutation[num--]); k = k - t * permutation[num + 1]; res.push_back(digits[t]); digits.erase(digits.begin() + t); } res.push_back(digits[k - 1]); return res; } };
相关文章推荐
- 304. Range Sum Query 2D - Immutable
- 对iOS 9 新增的控件 UIStackView 官方文档的翻译 第四部分
- 187. Repeated DNA Sequences
- 60. Permutation Sequence
- 手机GUI自动化测试介绍 | 有道技术沙龙博客
- C#中怎么生成36位的GUID
- UIViewContentMode各类型效果
- iOS开发~UITableViewCell重用机制总结
- android UI进阶之实现listview的分页加载
- libraries for bitcode must be generated from Xcode Archive or Install build forARM7 解决办法
- DelayQueue 队列
- 《iOS Human Interface Guidelines》——Contact Add Button
- UIStepper
- SQL Interview Questions
- PHP基础之如何调试PHP程序(HBuilder)
- pywinauto首页、文档和下载 - GUI 自动化测试框架 - 开源中国社区
- 原生的强大DOM选择器querySelector
- Android UI自动化测试最佳实践 - 51Testing软件测试网-中国软件测试人的精神家园
- [leetcode] 308. Range Sum Query 2D - Mutable 解题报告
- request.getParameter() 和request.getAttribute() 区别