數學問題Leetcode 60 Permutation Sequence
阿新 • • 發佈:2018-12-28
Leetcode 60
Permutation Sequence
- Problem Description:
返回給定n個數的第k個序列(按字典序排列)
具體的題目資訊:
https://leetcode.com/problems/permutation-sequence/description/ - Example:
- Solution:
class Solution {
public:
string getPermutation(int n, int k) {
string str = "";
vector<int > num;
int mod = 1;
for (int i = 1; i <= n; i++) {
num.push_back(i);
mod *= i; //計算n!
}
k--;
for (int i = 0; i < n; i++) {
mod /= n-i; //序列的第一位有(n-1)!中排列,接下來(n-2)!以此類推
int index = k/mod; //計算第一位在num中的位置
k %= mod; //得到下一位
stringstream ss;
ss << num[index];
str += ss.str(); //將數字轉換為字串
num.erase(num.begin()+index); //刪去已排列的數字
}
return str;
}
};