Permutations 解答
Question
Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
Solution
Traditional backtracking way to solve this problem.
1 public class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 Arrays.sort(nums); 4 int length = nums.length; 5 List<List<Integer>> result = new ArrayList<List<Integer>>(); 6 boolean[] visited = new boolean[length]; 7 8 dfs(nums, visited, new ArrayList<Integer>(), result); 9 return result; 10 } 11 12 private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) { 13 if (record.size() == nums.length) { 14 if (!result.contains(record)) 15 result.add(new ArrayList<Integer>(record)); 16 return; 17 } 18 for (int i = 0; i < nums.length; i++) { 19 if (!visited[i]) { 20 record.add(nums[i]); 21 visited[i] = true; 22 dfs(nums, visited, record, result); 23 // Restore 24 record.remove(record.size() - 1); 25 visited[i] = false; 26 } 27 } 28 } 29 }
Another solution is that we don't need to store visited status, but we just need to modify "nums" object.
1 class Solution: 2 def dfs(self, nums: List[int], record: List[int], result: List[List[int]]) -> None: 3 if not nums: 4 result.append(record) 5 for i in range(len(nums)): 6 self.dfs(nums[:i] + nums[i + 1:], record + [nums[i]], result) 7 8 def permute(self, nums: List[int]) -> List[List[int]]: 9 result = [] 10 self.dfs(nums, [], result) 11 return result