60. Permutation Sequence
阿新 • • 發佈:2018-05-09
bre set string owin solution order 記錄 amp color
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 for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Example 1: Input: n = 3, k = 3 Output: "213"Example 2: Input: n = 4, k = 9 Output: "2314"
找出n個數全排列的第k個序列。
解決:n個數全排列,第1~(n-1)!個數,肯定是1打頭的。
用一個數組記錄一下已經使用過的數字。
1 class Solution { 2 public: 3 int Allper(int n) { 4 int res = 1; 5 while (n > 0) 6 res *= n--; 7 return res; 8 } 9 string getPermutation(intn, int k) { 10 int cnt = 0; 11 vector<int> num(n); 12 string res; 13 int i; 14 int total; 15 while (res.size() < n) { 16 total = Allper(n - res.size() - 1); 17 i = 0; 18 while (i * total + cnt < k) 19 ++i;20 cnt += (i - 1) * total; 21 for (int j=0; j<n; ++j) { 22 if (num[j] == 0) 23 --i; 24 if (i == 0) { 25 num[j] = 1; 26 res += to_string(j + 1); 27 break; 28 } 29 } 30 } 31 return res; 32 } 33 };
60. Permutation Sequence