zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Permutations II

    题目:

    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2][1,2,1], and [2,1,1].

    题意:和I一样,找到所有的排列数 唯一不同的是 数组中会有重复的数字

    思路:加入visited判断该位置是否被选择了,避免选到自身,但这样还是会TLE,这时需要最关键的一步,开始dfs前对nums排序,这样,在dfs的时候 如果nums[i] == nums[i-1] 并且 visited[i-1] ==false的话 就continue,试想一下,这时的数字和前一个是一样的,前一个都没有被visited到,证明以这个数的排列已经完成了 那这个数字肯定是不用的了。

    代码:

    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            if(nums == null || nums.length == 0)
                return list;
                
            List<Integer> temp = new ArrayList<Integer>();
            boolean[] visited = new boolean[nums.length];
            
            Arrays.sort(nums);   // 关键1
            dfs(list, temp, nums, visited, 0);
            return list;
        }
        
        public void dfs(List<List<Integer>> list, List<Integer> temp, int[] nums, boolean[] visited, int count) {
            if(count == nums.length) {
                if(!list.contains(temp))
                    list.add(new ArrayList<Integer>(temp));
                return;
            }
            
            for(int i = 0 ; i < nums.length ; i++) {
                if(i > 0 && nums[i-1] == nums[i] && !visited[i-1]) //关键2
                    continue;
                if(visited[i])
                    continue;
                visited[i] = true;
                temp.add(nums[i]);
                dfs(list, temp, nums, visited, count+1);
                temp.remove(temp.size()-1);
                visited[i] = false;
            }
        }
    }
  • 相关阅读:
    解决App can’t be opened because it is from an unidentified developer
    Mac之当前目录打开终端
    Mac之安装zsh
    毕业论文之降低重复率
    Latex之希腊字母表 花体字母 实数集
    latex之插入数学公式
    好句收集
    Python之两个列表一起打乱
    Python之时间统计
    Python之正则表达式
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4703044.html
Copyright © 2011-2022 走看看