给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

 

示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

示例 2:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

 

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10
Related Topics
  • 数组
  • 回溯
  • \n
  • 👍 774
  • 👎 0
  • 题解

    回溯,同LeetCode刷题【剑指 Offer 38】字符串的排列

    代码

    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    
    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        List<List<Integer>> res;
        int[] nums;
        HashSet<Integer> samIndex;
        public List<List<Integer>> permuteUnique(int[] nums) {
            res = new ArrayList<>();
            samIndex = new HashSet<>();
            this.nums = nums;
            dfs(new ArrayList<>());
            return res;
        }
    
    
        private void dfs(List<Integer> list){
            if (list.size()==nums.length){
                res.add(new ArrayList<>(list));
                return;
            }
            HashSet<Integer> sameNum = new HashSet<>();
            for (int i = 0; i < nums.length; i++) {
                if (samIndex.contains(i)){
                    continue;
                }
                int num = nums[i];
                if (sameNum.contains(num)) {
                    continue;
                }
                samIndex.add(i);
                sameNum.add(num);
                list.add(num);
                dfs(list);
                samIndex.remove(i);
                list.remove(list.size() - 1);
            }
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)