1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution: def permute(self, nums: List[int]) -> List[List[int]]: """ first ans is empty for backtrack, start from [], for each item in nums, we add it to the end of curr, then do backtrack each item corresponds to a function call [1] -> [1,2] -> [1,2,3] -> [1,3] -> [1,3,2] [2] -> [2,1] -> [2,1,3] -> [2,3] -> [2,3,1] [3] -> [3,1] -> [3,1,2] -> [3,2] -> [3,2,1] for each call, we do iteration for nums, so it costs O(n) during iteration, for each item, we call backtrack, so there are O(n) backtrack """ def backtrack(curr): nonlocal ans if len(curr) == len(nums): ans.append(curr[:]) return for num in nums: if num not in curr: curr.append(num) backtrack(curr) curr.pop() ans = [] backtrack([]) return ans
|