///
Search

Permutation sequence

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 ์˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค