# 排列序列

给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。

按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

给定 n 和 k,返回第 k 个排列。

 

示例 1:

输入:n = 3, k = 3
输出:
"213"

示例 2:

输入:n = 4, k = 9
输出:
"2314"

示例 3:

输入:n = 3, k = 1
输出:
"123"

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int n = 3; int k = 3; string res; res = sol.getPermutation(n, k); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: string getPermutation(int n, int k) { string res; vector candidates; vector factorial(n + 1); factorial[0] = 1; int fact = 1; for (int i = 1; i <= n; i++) { candidates.push_back(i); fact *= i; factorial[i] = fact; } k -= 1; for (int i = n - 1; i >= 0; i--) { int index = k / factorial[i]; k = index * factorial[i]; res.push_back(candidates[index] + '0'); candidates.erase(candidates.begin() + index); } return res; } }; ``` ## 选项 ### A ```cpp class Solution { public: vector res; string getPermutation(int n, int k) { string track; traverse(track, n); return res[k - 1]; } void traverse(string &track, int n) { if (track.size() == n) { res.push_back(track); return; } for (int i = 1; i <= n; i++) { char c = i + '0'; if (find(track.begin(), track.end(), c) != track.end()) continue; track.push_back(c); traverse(track, n); track.pop_back(); } } }; ``` ### B ```cpp class Solution { public: string getPermutation(int n, int k) { string ans; vector st(n + 1); for (int i = 1; i <= n; i++) { int f = 1; for (int j = n - i; j >= 1; j--) f *= j; for (int j = 1; j <= n; j++) { if (!st[j]) { if (k <= f) { ans += to_string(j); st[j] = 1; break; } k -= f; } } } return ans; } }; ``` ### C ```cpp class Solution { public: int th; string ans; string getPermutation(int n, int k) { string s; vector vec(9, false); this->th = 0; backtrack(n, k, s, vec); return ans; } bool backtrack(int n, int k, string &s, vector &vec) { if (s.length() == n) { if (++th == k) { ans = s; return true; } } for (char c = '1'; c <= '1' + n - 1; c++) { if (vec[c - '1']) continue; s.push_back(c); vec[c - '1'] = true; if (backtrack(n, k, s, vec)) return true; s.pop_back(); vec[c - '1'] = false; } return false; } }; ```