力扣算法题—060第K个排列

给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。

按大小顺序列出所有排列情况,并一一标记,当 = 3 时, 所有排列如下:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

给定 n 和 k,返回第 k 个排列。

说明:

  • 给定 n 的范围是 [1, 9]。
  • 给定 的范围是[1,  n!]。

示例 1:

输入: n = 3, k = 3
输出: "213"

示例 2:

输入: n = 4, k = 9
输出: "2314"
 #include "_000库函数.h"

 //一打眼看到题目描述,就想起用排列算法
//时间有点长588ms class Solution {
public:
string getPermutation(int n, int k) {
vector<int>v;
for (int i = ; i <= n; ++i)
v.push_back(i);
--k;
while (next_permutation(v.begin(), v.end()) && --k);
string s = "";
for (auto a : v)
s += a + '';
return s;
}
}; //用一下递归
class Solution {
public:
string getPermutation(int n, int k) {
vector<int>v;
for (int i = ; i <= n; ++i)
v.push_back(i);
Combin(v, , );
string s = "";
for (auto a : v)
s += a + '';
return s;
}
void Combin(vector<int>&v, int k, int s) {
if (!k)return;
if (s >= v.size())--k;
for (int i = s; i < v.size(); ++i) {
swap(v[i], v[s]);
Combin(v, k, s + );
swap(v[i], v[s]);
}
}
}; //博客答案,没怎么看懂
//后期看懂再更新
//12ms
class Solution {
public:
string getPermutation(int n, int k) {
string res;
string num = "";
vector<int> f(n, );
for (int i = ; i < n; ++i) f[i] = f[i - ] * i;
--k;
for (int i = n; i >= ; --i) {
int j = k / f[i - ];
k %= f[i - ];
res.push_back(num[j]);
num.erase(j, );
}
return res;
}
}; void T060() {
Solution s;
cout << s.getPermutation(, ) << endl;
cout << s.getPermutation(, ) << endl;
}
上一篇:Sharepoint 2010 创建栏 计算栏


下一篇:HTML5资源汇总(更新游戏引擎cocos2d-html5)