LeetCode(Permutation Sequence)输出全排列中第k个排列
2014-04-10 05:23
525 查看
题目要求:
The set
total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
思路:
可以用递归遍历所有可能的排列 然后找出第k个。这样时间复杂度会很高.
仔细想一下可以找到一下规律:
n个数的的第k个排列为:
a1, a2, a3,...an;
接下来我们一个一个数的选取,如何确定第一个数应该是哪一个呢?选取第一个数后剩下全排列的个数为(n-1)! 所以选取的第一个数应该为第
K1 = k;
a1 = K1/(n-1)!位数字
同理当选完a1后只剩下n-1个数字,在确定第二个数应该选择哪个.
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
........
a(n-1) = K(n-1) / 1!
K(n-1) = k(n-2) % 2!
an = K(n-1)
代码:
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个数的的第k个排列为:
a1, a2, a3,...an;
接下来我们一个一个数的选取,如何确定第一个数应该是哪一个呢?选取第一个数后剩下全排列的个数为(n-1)! 所以选取的第一个数应该为第
K1 = k;
a1 = K1/(n-1)!位数字
同理当选完a1后只剩下n-1个数字,在确定第二个数应该选择哪个.
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
........
a(n-1) = K(n-1) / 1!
K(n-1) = k(n-2) % 2!
an = K(n-1)
代码:
class Solution { public: string getPermutation(int n, int k) { vector<int> num(n, 0); int perm_sum = 1; for(size_t i = 0; i < n; ++i) { num[i] = i + 1; perm_sum *= (i + 1); } string ret; //因为数组是从0到n-1的 所以基数从 0到k-1 --k; for(size_t i = 0; i < n; ++i) { perm_sum = perm_sum / (n - i); int selected = k / perm_sum; ret.push_back(num[selected] + '0'); //选择一个数后重新构造剩下的数组 for(size_t j = selected; j < n - i - 1; ++j) num[j] = num[j + 1]; k = k % perm_sum; } return ret; } };
相关文章推荐
- leetcode:Permutation Sequence (顺序排列第k个序列) 【面试算法题】
- LeetCode Permutation Sequence(求排列中的第k个排列是什么)
- Permutation Sequence 排列序列-第K个排列
- LeetCode 60. Permutation Sequence 全排列的第k个
- leetcode_60. Permutation Sequence 找n的全排列中的第k个序列
- [LeetCode]Permutation全排列和去重全排列
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- PermutationSequence,求第k个全排列
- LeetCode | Permutation Sequence(找到全排列中的第k个排列)
- Permutation Sequence 求第k个的排列序列 @LeetCode
- 输出全排列 (next_permutation)
- [LeetCode] Permutation Sequence
- Permutation Sequence -- leetcode
- 每天一道LeetCode-----找到第k个排列
- [LeetCode] Next Permutation、Permutations、Permutations II、Permutation Sequence
- LeetCode Permutation Sequence
- LeetCode之Permutation Sequence
- leetcode Permutation Sequence
- LeetCode Permutation Sequence
- leetcode Permutation Sequence