Loading

LeetCode 47 全排列II

LeetCode47 全排列II

题目描述

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

样例

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

算法分析

来自小呆呆

  • 从前往后枚举当前数组中没有选过的元素,由于相同的数保证从第一个开始用,直到最后一个,才会保证枚举的顺序不会出现重复的情况,若nums[i] == nums[i - 1],并且i - 1 位置元素未使用过,则表示前面的枚举顺序已经存在了该枚举情况,造成重复

时间复杂度

Java代码

class Solution {

    static List<List<Integer>> ans = new ArrayList<List<Integer>>();
    static boolean[] st;
    static List<Integer> t = new ArrayList<Integer>();

    static void dfs(int[] nums, int u){
        int n = nums.length;
        if(n == u){
            ans.add(new ArrayList<Integer>(t));
            return ;
        }

        for(int i = 0; i<n; i++){
            if(st[i]) continue;
            if(i > 0 && nums[i] == nums[i-1] && !st[i-1]) continue;
            t.add(nums[i]);
            st[i] = true;
            dfs(nums, u+1);
            st[i] = false;
            t.remove(t.size()-1);
            
        }
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        ans.clear();
        int n = nums.length;
        st = new boolean[n+10];
        Arrays.sort(nums);
        dfs(nums, 0);
        return ans;
    }
}
posted @ 2020-11-08 19:36  想用包子换论文  阅读(120)  评论(0)    收藏  举报