# leetcode 60:Permutation Sequence

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;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode 60:Permutation Sequence 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)