46
public static List<List<Integer>> permute(int[] nums) {
List<Integer> ret = new ArrayList<Integer>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
boolean[] read = new boolean[nums.length];
int deep = 0;
dfs(nums, ret, list, read, deep);
return list;
}
private static void dfs(int[] nums, List<Integer> ret, List<List<Integer>> list, boolean[] read, int deep) {
if (deep == nums.length)
{
List<Integer> copy = new ArrayList<Integer>();
copy.addAll(ret);
list.add(copy);
return;
}
for (int i = 0; i < nums.length; i++)
{
if (!read[i])
{
read[i] = true;
ret.add(nums[i]);
dfs(nums, ret, list, read, deep+1);
ret.remove(ret.size()-1);
read[i] = false;
}
}
}
47
public static List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<Integer> ret = new ArrayList<Integer>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
boolean[] read = new boolean[nums.length];
int deep = 0;
dfs(nums, ret, list, read, deep);
return list;
}
private static void dfs(int[] nums, List<Integer> ret, List<List<Integer>> list, boolean[] read, int deep) {
if (deep == nums.length)
{
List<Integer> copy = new ArrayList<Integer>();
copy.addAll(ret);
list.add(copy);
return;
}
for (int i = 0; i < nums.length; i++)
{
if (i > 0 && nums[i] == nums[i-1] && read[i-1] == false)
continue;
if (!read[i])
{
read[i] = true;
ret.add(nums[i]);
dfs(nums, ret, list, read, deep+1);
ret.remove(ret.size()-1);
read[i] = false;
}
}
}