题目地址:Permutation Sequence
题目简介:
给出集合[1,2,3,...,n],其所有元素共有种排列。
an'd按大小顺序列出所有排列情况,并一一标记,当n=3时,所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定n和k,返回第k个排列。
说明:
给定n的范围是[1,9],gei给定k的范围是[1,n]。
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
题目解析:
1、暴力:一次次消耗k。
C++版:
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums;
for (int i = 0; i < n; i++)
{
nums.push_back(i + 1);
}
while(--k)
{
next_permutation(nums.begin(),nums.end());
}
string ans;
for (int i = 0; i < n; i++)
{
ans += (nums[i] + '0');
}
return ans;
}
};
2、观察规律:
当n=3时,有6种组合情况,其中每个数字有三种情况。
从图中可以看到,当固定第一个数字时,还有种情况。
- 因为原始的字符串str为“123”,例如当序号i为1,2时,第一个数字为。
- 当第一个数字固定后,从原始字符串中把选择出的字符剔除,例如序号1,2时,还剩下“23”,因为确定了第一个位置还有剩下,剩下需要确定第个数字。
- 如此往返,确定n个数字。
C++版:
class Solution {
public:
int fac(int x){
int ans = 1;
if (x <= 1)
return ans;
while(x != 1)
{
ans *= x;
x--;
}
return ans;
}
string getPermutation(int n, int k) {
string nums;
for (int i = 1; i <= n; i++)
{
nums += ('0' + i);
}
string ans;
k--;
for (int i = 0; i < n; i++)
{
int temp = k / fac(n - i - 1);
ans += nums[temp];
nums.erase(temp,1);
k %= fac(n - i - 1);
}
return ans;
}
};
Python版:(今日份学习点:Python自带的阶乘函数math.factorial(n))
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nums = ['0'] * n
for i in range(n):
nums[i] = str(i + 1)
ans = ""
k -= 1
for i in range(n):
temp = int (k / math.factorial(n - i - 1))
ans += nums[temp]
nums.remove(nums[temp])
k %= math.factorial(n - i - 1)
return ans