Permutation Sequence
2015-09-04 13:47
459 查看
The set
permutations.
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.
class Solution {
public:
string getPermutation(int n, int k)
{
vector<int> nums(n);
int pCount = 1;
for(int i = 0 ; i < n; ++i) {
nums[i] = i + 1;
pCount *= (i + 1);
}
k--;
string res = "";
for(int i = 0 ; i < n; i++) {
pCount = pCount/(n-i);
int selected = k / pCount;
res += ('0' + nums[selected]);
for(int j = selected; j < n-i-1; j++)
nums[j] = nums[j+1];
k = k % pCount;
}
return res;
}
};
[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)
{
vector<int> nums(n);
int pCount = 1;
for(int i = 0 ; i < n; ++i) {
nums[i] = i + 1;
pCount *= (i + 1);
}
k--;
string res = "";
for(int i = 0 ; i < n; i++) {
pCount = pCount/(n-i);
int selected = k / pCount;
res += ('0' + nums[selected]);
for(int j = selected; j < n-i-1; j++)
nums[j] = nums[j+1];
k = k % pCount;
}
return res;
}
};
相关文章推荐
- 【POJ 3657】Haybale Guessing
- 树形dp hdu 4126 Genghis Khan the Conqueror
- deque,queue,stack,
- UIImageView的属性与方法
- 文件比较,文件夹比较-- vimdiff,beyond compare, compare suite, WinMerge,Kdiff3
- 文件比较,文件夹比较-- vimdiff,beyond compare, compare suite, WinMerge,Kdiff3
- InnoDB: The log sequence number in ibdata files does not match
- iOS ui界面vtf 开发
- UIday0801:UINavigationController视图控制器的属性和用法
- UI:登录窗的自定义键盘
- arduino与Processing通信问题
- UISearchBar 修改占位符的放大镜
- QuickNews新闻客户端源码
- HDU 1242 Rescue - DFS 回溯
- iOS开发之有趣的UI —— UIScrollerView 控件及案例
- Nqueen1.0
- QSqlQueryModel使用小结
- UIButtont特殊样式
- UILabe的特殊格式
- UIView