Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
Time: O(N!)
Space: O(N)
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] if nums is None or len(nums) == 0: return res my_set = set() cur_list = [] self.dfs(0, my_set, nums, cur_list, res) return res def dfs(self, level, my_set, nums, cur_list, res): if level == len(nums): res.append(list(cur_list)) return for i in range(len(nums)): if nums[i] in my_set: continue my_set.add(nums[i]) cur_list.append(nums[i]) self.dfs(level + 1, my_set, nums, cur_list, res) my_set.remove(nums[i]) cur_list.pop()
1 class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if (nums == null || nums.length == 0) { 5 return res; 6 } 7 helper(res, new ArrayList<>(), nums); 8 return res; 9 } 10 11 private void helper(List<List<Integer>> res, List<Integer> list, int[] nums) { 12 if (list.size() == nums.length) { 13 res.add(new ArrayList<>(list)); 14 return; 15 } 16 for (int num: nums) { 17 if (list.contains(num)) { 18 continue; 19 } 20 list.add(num); 21 helper(res, list, nums); 22 list.remove(list.size() - 1); 23 } 24 } 25 }
Solution 2:
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] if nums is None or len(nums) == 0: return res self.dfs(nums, 0, res) return res def dfs(self, array, level, res): if level == len(array): res.append(list(array)) return res for i in range(level, len(array)): array[level], array[i] = array[i], array[level] self.dfs(array, level + 1, res) array[i], array[level] = array[level], array[i]