from itertools import permutations
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nums = [elem+1 for elem in range(n)]
# self.permute(nums=nums)
for idx, num in enumerate(permutations(nums), start=1):
if idx == k:
temp = [str(e) for e in num]
ans = ''.join(temp)
return ans
@staticmethod
def permute(nums):
def backtracking(curr):
if len(curr) == len(nums):
ans.append(curr[:])
return
for num in nums:
if num not in curr:
curr.append(num)
backtracking(curr)
curr.pop()
ans = []
backtracking([])
return ans
JavaScript
๋ณต์ฌ
from itertools import permutations
import math
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nums = [elem+1 for elem in range(n)]
# self.permute(nums=nums)
for idx, num in enumerate(permutations(nums), start=1):
if idx == k:
temp = [str(e) for e in num]
ans = ''.join(temp)
return ans
def getPermutation2(self, n: int, k: int) -> str:
nums = [elem + 1 for elem in range(n)]
permutation = ''
k -= 1
while n > 0:
n -= 1
index, k = divmod(k, math.factorial(n))
permutation += str(nums[index])
nums.remove(nums[index])
return permutation
Python
๋ณต์ฌ
getPermutation2 ์ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๊ฒ ๋๋ฉด ์๊ฐ๋ณต์ก๋๋ฅผ ์ค์ผ ์ ์๊ฒ ๋๋ค