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.
public class Solution {
public List<List<Integer>> permute(int[] nums) {
Arrays.sort(nums);
int length = nums.length;
List<List<Integer>> result = new ArrayList<List<Integer>>();
boolean[] visited = new boolean[length]; dfs(nums, visited, new ArrayList<Integer>(), result);
return result;
} private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) {
if (record.size() == nums.length) {
if (!result.contains(record))
result.add(new ArrayList<Integer>(record));
return;
}
for (int i = 0; i < nums.length; i++) {
if (!visited[i]) {
record.add(nums[i]);
visited[i] = true;
dfs(nums, visited, record, result);
// Restore
record.remove(record.size() - 1);
visited[i] = false;
}
}
}
}
Another solution is that we don't need to store visited status, but we just need to modify "nums" object.
class Solution:
def dfs(self, nums: List[int], record: List[int], result: List[List[int]]) -> None:
if not nums:
result.append(record)
for i in range(len(nums)):
self.dfs(nums[:i] + nums[i + 1:], record + [nums[i]], result) def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.dfs(nums, [], result)
return result