47.全排列2
给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
示例 1:
1 2 3 4 5
| 输入:nums = [1,1,2] 输出: [[1,1,2], [1,2,1], [2,1,1]]
|
示例 2:
1 2
| 输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class Solution { private List<Integer> path=new ArrayList<>(); private boolean[] onPath; private final List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); onPath = new boolean[nums.length]; dfs(0,nums); return ans; }
private void dfs(int i,int [] nums) { if (i == nums.length) { ans.add(new ArrayList<>(path)); return; }
for (int j = 0; j < nums.length; ++j) { if (!onPath[j]) { path.add(nums[j]); onPath[j] = true; dfs(i + 1,nums); path.remove(path.size()-1); onPath[j] = false; } while (j < nums.length - 1 && nums[j] == nums[j + 1]&&onPath[j]==false) { ++j; } } } }
|