1. 程式人生 > >【LeetCode】60. Permutation Sequence(C++)

【LeetCode】60. Permutation Sequence(C++)

地址:https://leetcode.com/problems/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 for n =

3 n = 3 :

  • 123
  • 132
  • 213
  • 231
  • 312
  • 321

Given n n and k

k , return the k t h k^{th} permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.
  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: “213”

Example 2:

Input: n = 4, k = 9
Output: “2314”

理解:

需要求一個全排列的第k個。
注意全排列的順序是符合字典序的。
根據k,和n-1個元素的全排列的個數,我們可以確定第位的數字是什麼。
比如上面的123,如果k是3,則可以得到第一位是2
然後找13這個組合的全排列裡的第一個,就是13了。

實現:

class Solution {
public:
	string getPermutation(int n, int k) {
		vector<int> fac(n,1);
		for (int i = 1; i < n; ++i) {
			fac[i] = i*fac[i - 1];
		}
		string res(n, '0');
		for (int i = 0; i < n; ++i)
			res[i] += i + 1;
		--k;
		for (int i = 0; i < n; ++i) {
			int index = i + k / fac[n - 1 - i];
			char c = res[index];
			for (; index > i; --index)
				res[index] = res[index - 1];
			res[i] = c;
			k %= fac[n - 1 - i];
		}
		return res;
	}
};