最佳解法,类似阶乘公式!!!
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> numsList = new ArrayList<>();
for (int val : nums) {
numsList.add(val);
}
dfs(numsList, 0, res);
return res;
}
public void dfs(List<Integer> numsList, int idx, List<List<Integer>> res) {
if (idx == numsList.size() - 1) {
res.add(new ArrayList<>(numsList));
return;
}
HashSet<Integer> set = new HashSet<>(); // 不加set则是普通全排列的解法
for (int i = idx; i < numsList.size(); ++i) {
if (set.contains(numsList.get(i))) {
continue;
}
set.add(numsList.get(i));
swap (numsList, idx, i);
dfs(numsList, idx + 1, res);
swap (numsList, idx, i);
}
}
public void swap (List<Integer> numsList, int i, int j) {
int tmp = numsList.get(i);
numsList.set(i, numsList.get(j));
numsList.set(j, tmp);
}
}