LeetCode - Permutation Sequnce 题解
来源:互联网 发布:七日杀小人物模型数据 编辑:程序博客网 时间:2024/06/10 04:15
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.
分析:可以一个一个找next permulation 不过会超时
class Solution {private: void getBigger(vector<int> &numbers){ int pos = numbers.size() - 1; while(numbers[pos - 1] > numbers[pos]) pos--; pos--; int xpos = numbers.size() - 1; while(numbers[xpos] < numbers[pos]) xpos--; int x = numbers[xpos]; int t = numbers[pos]; numbers[pos] = numbers[xpos]; numbers[xpos] = t; int i = pos + 1, j = numbers.size() - 1; while(i < j){ t = numbers[i]; numbers[i] = numbers[j]; numbers[j] = t; i ++; j --; } }public: string getPermutation(int n, int k) { vector<int> numbers(n); for(int i = 1; i <= n; i++){ numbers[i - 1] = i; } for(int i = 1; i < k; i++) getBigger(numbers);//,printVector<int>(numbers); string ans; for(auto x : numbers){ char ch[25]; sprintf(ch,"%d",x); ans += string(ch); } return ans; }};
class Solution {private: int getJieCheng(int m){ int ans = 1; for(int i = 1; i <= m;i ++){ ans *= i; } return ans; }public: string getPermutation(int n, int k) { vector<int> numbers; for(int i = 1; i <= n; i++) numbers.push_back(i); string ans; for(int m = n - 1; m >= 0; m--){ int l = getJieCheng(m); int i = 0; while(k > l){ k -= l; i++; } char ch[10]; sprintf(ch, "%d", numbers[i]); ans += string(ch); numbers.erase(numbers.begin() + i); } return ans; }};
0 0
- LeetCode - Permutation Sequnce 题解
- LeetCode题解:Next Permutation
- LeetCode题解:Next Permutation
- leetcode 题解 || Next Permutation 问题
- LeetCode 题解(169): Permutation Sequence
- LeetCode 题解(241) : Palindrome Permutation
- leetcode题解-31. Next Permutation
- leetcode题解-31. Next Permutation
- Leetcode题解-31. Next Permutation
- sequnce
- LeetCode 题解(4):Next Permutation
- LeetCode题解——Permutation总结
- LeetCode 题解(242) : Palindrome Permutation II
- Permutation 题解
- LeetCode Permutation
- [LeetCode] Permutation
- LeetCode-Permutation
- Leetcode--Permutation
- 探索Oracle之数据库升级二 11.2.0.3升级到11.2.0.4完整步骤
- 集深数据系统V5-动态改变列
- 紫荆之声团委微信应用第一次迭代感想
- Linux-----内核移植篇
- perl中eval函数的两种使用方式
- LeetCode - Permutation Sequnce 题解
- 【Java技术点滴】——精简实现图片处理
- 面试题(4)和为S的两个数字
- MyReport报表引擎2.6.5.1新功能
- 对于String类的学习
- bign的结合有问题无法运行
- 踏进网络游戏的第一步
- 什么叫不会聊天?
- WebGIS中的坐标系