n=4,k=9
There are 4 groups of n=4 (1-6,7-12,13-18,19-24), 9 belongs to the second one. So the first number is the second one of [1,2,3,4], which is 2.
There are 3 groups of n=3 (1-2,3-4,5-6), the remainder of 9/6 is 3, belongs to the second group. So the second number is the second number of [1,3,4], which is 3.
There are 2 groups of n=2 (1,2), the remainder of 3/2 is 1, belongs to the first group. So the third number is the first one of [1,4], which is 1.
Wrong version (lose k-=1)
input: 3 3
output: “231"
expected: “213"
class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
ans = ''
fact = [1] * n
num = [str(i) for i in range(1, 10)]
for i in range(1, n):
fact[i] = fact[i - 1] * i
for i in range(n, 0, -1):
first = k // fact[i - 1]
print(k,first)
k %= fact[i - 1]
ans += num[first]
num.pop(first)
return ans
class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
ans = ''
fact = [1] * n
num = [str(i) for i in range(1, 10)]
for i in range(1, n):
fact[i] = fact[i - 1] * i
k -= 1
for i in range(n, 0, -1):
first = k // fact[i - 1]
print(k,first)
k %= fact[i - 1]
ans += num[first]
num.pop(first)
return ans