This code gives an error: 'UnboundLocalError: local variable 'k' referenced before assignment'
. I understand it's because the outer function doesn't pass the parameter, but why does res = []
works but not k =0
?
class Solution:
def getPermutation(self, n: int, k: int) -> str:
res = []
k = 0
def backtrack(nums, path):
if not nums:
k = k - 1
if k == 0:
res.append(path)
return
if k < 0: return
for i in range(0, len(nums)):
backtrack(nums[:i] + nums[i + 1:], path + [nums[i]])
backtrack(list(range(1, n + 1)), [])
return res
print(Solution().getPermutation(3, 1))