# leetcode 60:Permutation Sequence

135人阅读 评论(0)

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):

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

Given n and k, return the kth permutation sequence.

class Solution {
public:
string getPermutation(int n, int k) {
vector<char> nums;
for (int i = 1; i <= n; i++) nums.push_back(i+'0');
count = 0;
string result;
back(0, n, k, nums, result);
return result;
//return result.substr(0,n);
}
void back(int index, int size, int k, vector<char>& nums,string &result)
{
if (index >= size)
{
count++;
if (count >= k)	result.assign(nums.begin(),nums.end());
return;
}
for (int i = index; i<size && count<k; i++)
{
swap(nums[i], nums[index]);
back(index + 1, size, k, nums,result);
swap(nums[i], nums[index]);
}
}
private:
int count;
};

class Solution {
public:
string getPermutation(int n, int k) {
vector<char> nums;
int factorial = 1;
string res;
for (int i = 1; i <= n; i++)
{
factorial *= i;
nums.push_back(i + '0');
}
k--;
for (int i = 0; i < n; i++)
{
factorial = factorial / (n - i);
int select = k / factorial;
res.push_back(nums[select]);
for (int j = select; j < n - i - 1; j++)
nums[j] = nums[j + 1];
k = k % factorial;
}
return res;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：45337次
• 积分：2534
• 等级：
• 排名：第14965名
• 原创：215篇
• 转载：20篇
• 译文：0篇
• 评论：2条
文章分类
最新评论