60. Permutation Sequence
来源:互联网 发布:手机域名是什么 编辑:程序博客网 时间:2024/06/05 19:43
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.
class Solution {public: string getPermutation(int n, int k) { int total = factorial(n); string candidate = string("123456789").substr(0,n); string res(n,' '); for(int i = 0; i < n; i++){ total /= (n-i); int tmp = (k-1)/total; res[i] = candidate[tmp]; candidate.erase(tmp,1); k-=total*tmp; } return res; } int factorial(int n){ int res = 1; for(int i = 2; i <= n; i++){ res*=i; } return res; }};
求第k个排列,通过C++里面的next_permutation()函数求解,超时,然后通过筛选的方式求解,通过逐个确定每个位置的数字,首先通过通过(k-1)/(n-1)!固定某个数。通过m=(k-1)/(n-1)!,该数就是原数组的第m个数,第一个数固定后,我们从candidate数组中删除该数,那么就相当于在当前src的基础上求第k - m*(n-1)!个排列。通过n次逐个确定每个位置的值。
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
- Java基础:网络编程
- [GDOI2017模拟]最大值(贪心+递推)
- html5 websocket
- vs2015 +wdk10 +WIN10 +VMWARE12 驱动开发环境搭建
- 解决ExpandableListView中子元素无法点击,OnChildClickListener无效
- 60. Permutation Sequence
- 开源飞控介绍
- 适配篇-爱上自适应(最简单的解决方案)
- 解决跨域问题
- 观察者模式实例
- 设置ntpdate服务开机启动校验时间
- erlang dialyzer使用
- asynctask基本使用
- c# vs2010 连接access数据库