Permutation Sequence
2013-11-14 20:02
513 查看
The set
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.
代码:
[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.
代码:
string getPermutation(int n, int k) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int fac[10]; fac[0] = 1; for(int i = 1; i <= 9; i++){ fac[i] = fac[i-1]*i; } string result = ""; vector<int> nums; for(int i = 0; i < n; i++) nums.push_back(i+1); for(int i = n; i >= 1; i--){ if(k <= fac[i-1]){ result += (nums[0]+'0'); nums.erase(nums.begin()); } else if(k == fac[i]){ for(vector<int>::iterator it = nums.end()-1; it >= nums.begin(); it--){ result += (*it+'0'); } break; } else{ int j = (k-1)/fac[i-1]+1; k = k - (j-1)*fac[i-1]; vector<int>::iterator it = nums.begin(); while(j > 1){ it++; j--; } result += (*it+'0'); nums.erase(it); } } return result; }
相关文章推荐
- CoreData之FetchRequestController
- poj2478 Farey Sequence 欧拉函数的应用
- poj2478 Farey Sequence 欧拉函数的应用
- [翻译]API Guides - Bound Services
- BlockingQueue【转】
- EasyUI移除select校验
- webDriver.Close() 和 webDriver.Quit() 、webDriver.Dispose() 的区别
- 史上最简洁的UITableView Sections 展示包含NSDicionary 的NSArray
- SOAPUI 压力测试的指标项说明
- Adobe Flash Builder 4.7破解方法(绝对可用)
- LA 2678 Subsequence
- SlidingMenu官方实例分析6——ResponsiveUIActivity
- 在UINavigationController下只要一个页面支持转屏
- 分享初学者在Web设计的七大误区
- ArcGIS的 UID
- 通过UIView获取UIViewController
- UIView 的 autoresizingMask 属性 详解。
- 调用原生媒体音量控制UI
- Permutation Sequence [LeetCode]
- UIDynamicAnimator