[LeetCode]Permutation Sequence
2015-08-12 22:54
323 查看
题目
Number: 60Difficulty: Medium
Tags: Backtracking, Math
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
nand
k, return the
kthpermutation sequence.
Note: Given n will be between 1 and 9 inclusive.
题解
求解n个数的全排列中第
k个排列。
对于
n位数的全排列,如果第一个数字是
1的排列有
(n-1)!个,同样可得出每一位数字。
代码
[code]string getPermutation(int n, int k) { string res(n, '1'); vector<int> l; for(int i = 0; i < n; i ++){ l.push_back(i); res[i] = '1' + i; } if(k == 1) return res; vector<int> fac(n, 1); for(int i = n - 3; i >= 0; i--){ fac[i] = fac[i + 1] * (n -i - 1); } k = k - 1; for(int i = 0; i < n; i++){ int select = k / fac[i]; k %= fac[i]; res[i] = l[select ] + '1'; remove(l.begin(), l.end(), l[select]); } return res; }
相关文章推荐
- OC-UI部分,简单的登陆界面简单代码
- Domino Angular 前端UI开发
- arm交叉编译器gnueabi、none-eabi、arm-eabi、gnueabihf、gnueabi区别
- DCIM 用 UIScrollView 和UIPageControl
- js实现EasyUI-datagrid前台分页
- Leetcode63 Unique Paths II
- UIPageControl
- UI 06 _ 7种手势
- 消息队列(message queue)产生的背景、常用的技术
- hdu 1297 Children’s Queue(递推和高精)
- IOS--UI--NSThread 和GCD 总结
- Design Pattern -- Builder
- UI05 _ 分段控件 -- UISegmentedControl
- UIImageView+GestureRecognizer
- prim Building a Space Station
- iOS开发-UIScreenEdgePanGestureRecognizer实战
- UI 05 _ GIF 图的播放
- 优化UITableViewCell高度计算的那些事
- 读书笔记-APUE第三版-(11)线程
- UIButton在Disabled状态下标题混乱的问题