Permutation Sequence
2015-12-18 23:57
519 查看
Permutation Sequence
Total Accepted: 44618 Total Submissions: 187104 Difficulty: MediumThe 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.
先看个例子:假设n=4,k=8
1.固定第0个位置后面有3!=6中排列,
2.固定第0,1个位置后面有2!=2中排列
pos: 0 1 2 3
3! 2! 1! 0
第0个位置每固定一个字符,后面就有6种排列,所以第0个位置分别为'1','2','3','4'时分别对应的排列的范围是:
序号 字符 范围
0 '1' 第1-6个排序
1 '2' 第7-12个排列
2 '3' 第13-18个排列
3 '4' 第19-24个排列
k=8 属于第7-12个排列,其实就是(k-1)/6个序号的排列
排好第0个位置的字符后,按同样的方法排第1个位置就可以了,此时,k=k%6=8%6=2;
class Solution { public: string getPermutation(int n, int k) { string s; int fact = 1; for(int i=1;i<=n;i++){ s.push_back(i+'0'); fact *= i; } k--; string res while(n){ fact /= n; int pos = k/fact; res.push_back(s[pos]); s.erase(s.begin()+pos); k = k%fact; --n; } return res; } };
相关文章推荐
- [知识点随笔] UIView--transform 属性
- Cstyle的札记,Freertos内核详解,第5.0篇
- 1062. Talent and Virtue (25)【排序】——PAT (Advanced Level) Practise
- codeforces Police Recruits
- 快速理解RequireJs中的config
- hdu2152 Fruit (背包dp)
- NSValue用法
- Farey Sequence(Poj2478)(快速求欧拉函数)
- GPUImageMovie播放控制
- datagrid分页
- 38 用break和continue改变流程 课后
- 在主函数中提示用户输入用户名和密码。另写一方法来判断用户输入是否正确。该方法分别返回一个bool类型的登录结果和和一个string类型的登录信息。如登录成功,返回true及“登录成功”,若登录失败则返回false及“用户名错误”或“密码错误”(使用out参数)
- 17-1 UI高级可视化设计
- 15 UITabBarController、block高级(+UIMenuController_UIPasteBoard、MBProgressHud)
- 14-1 UITableView综合-模态viewController、单例(LED,Neon)
- 组件_ UIToolbar 与 组件_UISearchBar
- UITableView的使用
- 13 自定义cell、cell自适应高度、 多种类型的cell混合使用、 UITableViewController、model类
- <LeetCode OJ> 303. Range Sum Query - Immutable
- 12 UITableView编辑和移动 、UITableViewController、(+UIDatePicker)