LeetCode Permutation Sequence,permutationleetcode
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, k,比如n=4, k=17。首Crowdsourced Security Testing道n以下的組合數有6,2,1。那麼17 = 2*6 + 2*2 + 1,
由於權值6的倍數是2,且有剩餘,所以第4位(最高位)的值是從“1234”中選第3小的數,也就是3;
由於權值2的倍數是2,且有剩餘,所以第3位的值是從“124”中選第3小的數,也就是4;
由於權值1的倍數是1,且沒有剩餘,所以第2位的值是從“12”中選第1小的數,也就是1;
最後剩下數,逆序追加到後面。
class Solution {public: string remove(string s, int index, char &c) { c = s[index-1]; string s1 = s.substr(0, index-1); string s2 = s.substr(index); return s1 + s2; } string getPermutation(int n, int k) { if (n > 9 || n < 1) return ""; string temp = "123456789"; int A[9] = {1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; if (A[n-1] < k) return ""; string s = temp.substr(0, n); if (k == 1) return s; if (k == A[n-1]) { reverse(s.begin(), s.end()); return s; } string ans = ""; char c; for (int i = n-2; i >= 0; i--) { int m = 0; if (k < A[i]) { s = remove(s, 1, c); ans += c; continue; } while (k >= A[i]) { k -= A[i]; m++; } if (k == 0) { s = remove(s, m, c); ans += c; reverse(s.begin(), s.end()); return ans + s; } else { s = remove(s, m+1, c); ans += c; } } return ans; }};