Leetcode算法学习日志-60 Permutation Sequence
2017-10-26 11:12
597 查看
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):
"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,可以构建n的所有排列的排列树,树的叶子数代表总的排列数,共n!个,对于第一层的n个子树,每个子树包含(n-1)!个序列,通过k与(n-1)!的取商取余,可以逐步寻找到相应解,c++代码如下:class Solution {
private:
int N;//total path in each layer
int curPath;
int K;//the order in each layer
public:
int pathNumber(int layer) {
int i;
curPath = 1;
for (i = 1; i <= (N - layer); i++) {
curPath = curPath*i;
}
int temp = K / (curPath / (N - layer));
if (K % (curPath / (N - layer)) == 0) {
K = curPath / (N - layer);
return temp - 1;
}
else {
K = K % (curPath / (N - layer));
return temp;
}
}
string getPermutation(int n, int k) {
N = n;
K = k ;
string res;
vector<int> num;
int i;
for (i = 1; i <= n; i++) {
num.push_back(i);
}
if (n == 1)
return "1";
int whichWay;
for (i = 0; i<n; i++) {
whichWay = pathNumber(i);
res.push_back('0'+num[whichWay]);
num.erase(num.begin() + whichWay);
}
//res.push_back(num[0]);
return res;
}
};
相关文章推荐
- Leetcode算法学习日志-54 Spiral Matrix
- Leetcode算法学习日志-594 Longest Harmonious Subsequence
- Leetcode算法学习日志-86 Partition List
- Leetcode算法学习日志-743 Network Delay Time
- Leetcode算法学习日志-215 Kth Largest Element in an Array
- Leetcode算法学习日志-576 Out of Boundary Paths
- Leetcode算法学习日志-399 Evaluate Division
- Leetcode算法学习日志-486 Predict the Winner
- Leetcode算法学习日志-241 Different Ways to Add Parentheses
- Leetcode算法学习日志-737 Sentence Similarity II
- Leetcode算法学习日志-611 Valid Triangle Number
- Leetcode算法学习日志-452 Minimum Number of Arrows to Burst Balloons
- Leetcode算法学习日志-673 Number of Longest Increasing Subsequence
- Leetcode算法学习日志-563 Binary Tree Tilt
- Leetcode算法学习日志-553 Optimal Division
- Leetcode算法学习日志-257 Binary Tree Paths
- Leetcode算法学习日志-447 Number of Boomerangs
- Leetcode算法学习日志-137 Single Number II
- Leetcode算法学习日志-561 Array Partition I
- Leetcode算法学习日志-752 Open the Lock