From d3c41547edaebc884170f0070990c22601adf085 Mon Sep 17 00:00:00 2001 From: Akruti Date: Wed, 19 Oct 2022 08:56:18 +0530 Subject: [PATCH] Changes made by akruti, added a new python leetcode problem --- Python/PermutationSequence.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/PermutationSequence.py diff --git a/Python/PermutationSequence.py b/Python/PermutationSequence.py new file mode 100644 index 0000000..92a5d2b --- /dev/null +++ b/Python/PermutationSequence.py @@ -0,0 +1,35 @@ +#Problem link - https://leetcode.com/problems/permutation-sequence/ +class Solution(object): + def getPermutation(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + # let permutations with first identical num be a block + # target in (k - 1) / (n - 1)! block + remain = range(1, n + 1) + if k <= 1: + return ''.join(str(t) for t in remain) + total = 1 + for num in remain[:-1]: + total *= num + res = self.do_getPermutation(remain, total, n - 1, k - 1) + return ''.join(str(t) for t in res) + + + def do_getPermutation(self, remain, curr, n, k): + if n == 0 or k <= 0 or curr == 0: + return remain + # which block + step = k / curr + # remain k value + k %= curr + curr /= n + res = [remain[step]] + self.do_getPermutation(remain[:step] + remain[step + 1:], curr, n - 1, k) + return res + +if __name__ == '__main__': + s = Solution() + print s.getPermutation(3, 2) + # print s.getPermutation(2, 2) \ No newline at end of file