[LeetCode]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):
"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.
解题思路:
按照上一题的思路,暴力破解,超时了,k可以超过n!,冏!代码如下,代码折叠,别打开:
class Solution {
public:
string getPermutation(int n, int k) {
string result(n, '0');
for (size_t i = 0; i < result.size(); ++i) {
result[i] += i + 1;
}
for (size_t i = 0; i < k; ++i) {
nextPermutation(result);
}
return result;
}
void nextPermutation(string& str) {
int i;
int j;
// From right to left, find the first item(PartitionNumber) which violates the increase trend
for (i = str.size() - 2; i >= 0; --i) {
if (str[i] < str[i + 1]) break;
}
// From right to left, find the first item(ChangeNumber) which is larger than PartitionNumber
for (j = str.size(); j >= i; --j) {
if (str[j] > str[i]) break;
}
// swap PartitionNumber and ChangeNumber
if (i >= 0) {
swap(str[i], str[j]);
}
// reverse all after PartitionNumber index
reverse(str.begin() + i + 1, str.end());
}
};
转载:http://www.cnblogs.com/tenosdoit/p/3721918.html
有没有什么方法不是逐个求,而是直接构造出第k个排列呢?我们以n = 4,k = 17为例,数组src = [1,2,3,...,n]。
第17个排列的第一个数是什么呢:我们知道以某个数固定开头的排列个数 = (n-1)! = 3! = 6, 即以1和2开头的排列总共6*2 = 12个,12 < 17, 因此第17个排列的第一个数不可能是1或者2,6*3 > 17, 因此第17个排列的第一个数是3。即第17个排列的第一个数是原数组(原数组递增有序)的第m = upper(17/6) = 3(upper表示向上取整)个数。
1 class Solution { 2 public: 3 string getPermutation(int n, int k) { 4 int total = factorial(n); 5 string candidate = string("123456789").substr(0, n); 6 string result(n, '0'); 7 for (int i =0; i < n; ++i) { 8 total /= (n - i); 9 int index = (k - 1) / total; 10 result[i] = candidate[index]; 11 candidate.erase(index, 1); 12 k -= index * total; 13 } 14 15 return result; 16 } 17 private: 18 int factorial(int n) { 19 int result = 1; 20 for (int i = 2; i <= n; ++i) { 21 result *= i; 22 } 23 24 return result; 25 } 26 };

浙公网安备 33010602011771号