|
| 1 | +import math |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + # brute force, find all permutations and return the k-th permutation (slow, LC submission time limit exceed) |
| 6 | + def getPermutation(self, n: int, k: int) -> str: |
| 7 | + def permute_rec(nums, start): |
| 8 | + if start >= len(nums): |
| 9 | + stringFormat = "" |
| 10 | + for num in nums: |
| 11 | + stringFormat += str(num) |
| 12 | + allPermutations.append(stringFormat) |
| 13 | + |
| 14 | + for i in range(start, len(nums)): |
| 15 | + nums[start], nums[i] = nums[i], nums[start] |
| 16 | + permute_rec(nums, start+1) |
| 17 | + nums[start], nums[i] = nums[i], nums[start] |
| 18 | + |
| 19 | + nums = [n+1 for n in range(n)] |
| 20 | + allPermutations = list() |
| 21 | + permute_rec(nums, 0) |
| 22 | + allPermutations.sort() |
| 23 | + return allPermutations[k-1] |
| 24 | + |
| 25 | + # smarter way from LC discuss (using mathematics) |
| 26 | + """ |
| 27 | + One main thing to consider is that when you have a five digit number possible numbers are 1,2,3,4,5. |
| 28 | + So the number of permutations that start with 1 are (5-1)! = 4! |
| 29 | + Similarly with 2 and 3 and 4 and 5. |
| 30 | + So if the k = 32 it means that i need to cross all the possibilites with 1 which are 24. and then check in the possibilties that start with 2. now we have crossed 24 possibilties so 32-24=8 are remaining. |
| 31 | + Now repeat the whole process with second significant digit. |
| 32 | + """ |
| 33 | + |
| 34 | + def getPermutation_smart(self, n: int, k: int) -> str: |
| 35 | + nums = [n+1 for n in range(n)] |
| 36 | + answer = "" |
| 37 | + while nums: |
| 38 | + fact = len(nums)-1 |
| 39 | + numPermEach = math.factorial(fact) |
| 40 | + indexOfNumToAppend = k // numPermEach |
| 41 | + if k % numPermEach == 0: |
| 42 | + indexOfNumToAppend -= 1 |
| 43 | + answer += str(nums[indexOfNumToAppend]) |
| 44 | + nums.pop(indexOfNumToAppend) |
| 45 | + k -= indexOfNumToAppend * numPermEach |
| 46 | + return answer |
| 47 | + |
| 48 | + |
| 49 | +sol = Solution() |
| 50 | +n = 3 |
| 51 | +k = 4 |
| 52 | +print(sol.getPermutation_smart(n, k)) |
0 commit comments