• LeetCode 47. Permutations II


    LeetCode 47. Permutations II (全排列II)

    题目

    链接

    https://leetcode.cn/problems/permutations-ii/

    问题描述

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

    示例

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

    提示

    1 <= nums.length <= 8
    -10 <= nums[i] <= 10

    思路

    和全排列相同,只需要多设置一个used数组,用于存放是否用过。

    复杂度分析

    时间复杂度 O(n2)
    空间复杂度 O(n)
    

    代码

    Java

        List<List<Integer>> ans = new LinkedList<>();
        LinkedList<Integer> path = new LinkedList<>();
    
        public List<List<Integer>> permuteUnique(int[] nums) {
            boolean[] used = new boolean[nums.length];
            Arrays.sort(nums);
            trace(nums, used);
            return ans;
        }
    
        public void trace(int[] nums, boolean[] used) {
            if (path.size() == nums.length) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < nums.length; i++) {
                if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) {
                    continue;
                }
                if (used[i] == false) {
                    used[i] = true;
                    path.add(nums[i]);
                    trace(nums, used);
                    path.remove(path.size() - 1);
                    used[i] = false;
                }
            }
        }
    
  • 相关阅读:
    sharepoint 2013 configure my site
    格式化xml
    斗罗大陆
    spring的beans.xml的配置
    jdom学习:读取xml文件
    java中加载xml文件方法
    struts2中IOC控制反转应用
    struts2.xml的配置与技巧
    struts2中的路径问题
    struts.xml详细配置
  • 原文地址:https://www.cnblogs.com/blogxjc/p/16375746.html
Copyright © 2020-2023  润新知