全排列Ⅱ

Leetcode题目描述

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

回溯解法/

  • 与原来的全排列问题相似,关键在于去重。可以采用笨蛋一点方法:依次全部遍历,如果已经存在相同结果的丢弃。利用HaspMap进行判断
  • 优化的思想:可以在原有基础上进行判断:位置不同但是数值相同的本次可以直接跳过此次循环
class Solution {
    HashMap<List<Integer>,Integer> hashmap = new HashMap<List<Integer>,Integer>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<Integer> tmp = new ArrayList<Integer>();
        List<List<Integer>> res = new ArrayList<>();


        int n = nums.length;
        for(int i = 0; i < n; i++){
            tmp.add(nums[i]);
        }
        backtrack(0, n, tmp, res);
        return  res;
    }
    public void backtrack(int first, int n , List<Integer> tmp, List<List<Integer>> res){
        if(first == n && !hashmap.containsKey(tmp)){
            hashmap.put(tmp,1);
            res.add(new ArrayList<Integer>(tmp));
        }
        
        for(int i = first; i < n; i++){
            Collections.swap(tmp, first, i);
            backtrack(first + 1, n , tmp, res);
            Collections.swap(tmp, first, i);
        }
    }
}
原文地址:https://www.cnblogs.com/Di-iD/p/13784946.html