Given a list of numbers, return all possible permutations.
Notice
You can assume that there is no duplicate numbers in the list.
Example
For nums = [1,2,3]
, the permutations are:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
java
public class Solution {
/*
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (nums == null) {
return result;
}
if (nums.length == 0) {
result.add(new ArrayList<Integer>());
return result;
}
dfs(nums, new ArrayList<Integer>(), new HashSet<Integer>(), result);
return result;
}
private void dfs(int[] nums,
List<Integer> path,
Set<Integer> set,
List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
continue;
} else {
set.add(nums[i]);
path.add(nums[i]);
dfs(nums, path, set, result);
set.remove(nums[i]);
path.remove(path.size() - 1);
}
}
}
}
python
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
if nums is None:
return []
if len(nums) == 0:
return [[]]
result = []
self.dfs(nums, [], set(), result)
return result
def dfs(self, nums, path, table, result):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if nums[i] in table:
continue
else:
table.add(nums[i])
path.append(nums[i])
self.dfs(nums, path, table, result)
path.pop()
table.remove(nums[i])