给定一个数字列表,返回其所有可能的排列。
样例
给出一个列表[1,2,3]
,其全排列为:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
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>> res = new ArrayList<>();
if(nums == null)
return res;
if(nums.length == 0)
{
res.add(new ArrayList<Integer>());
return res;
}
ArrayList<Integer> list = new ArrayList<>();
dfs(res, list, nums);
return res;
}
private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] nums) {
int n = nums.length;
if(list.size() == n)
{
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0;i < n;i++) {
if(list.contains(nums[i]))
continue;
list.add(nums[i]);
dfs(res, list, nums);
list.remove(list.size() - 1);
}
}
}