zoukankan      html  css  js  c++  java
  • LeetCode 47. Permutations II (全排列 II)

    题目标签:Backtracking

      利用dfs,建立一个 tempList, 递归加入每一个数字,利用 boolean[] used 来跳过 用过的数字,还有跳过重复的组合。

      具体看code。

      

    Java Solution: 

    Runtime:  1 ms, faster than 99.60 % 

    Memory Usage: 41.7 MB, less than 11.94 %

    完成日期:11/08/2019

    关键点:建立 boolean[] used

    class Solution {
        
        List<List<Integer>> res;
        
        public List<List<Integer>> permuteUnique(int[] nums) {
            res = new ArrayList<>();
            List<Integer> tempList = new ArrayList<>();
            boolean[] used = new boolean[nums.length];
            Arrays.sort(nums);
            DFS(nums, tempList, used);
            
            return res;
        }
        
        private void DFS(int[] nums, List<Integer> tempList, boolean[] used) {
            if(tempList.size() == nums.length) {
                res.add(new ArrayList<>(tempList));
                return;
            }
    
            for(int i=0 ; i<nums.length; i++) {
                if(used[i])
                    continue;
                if(i>0 && nums[i-1] == nums[i] && !used[i-1]) // if it is a duplicated permutation, skip
                    continue;
    
                used[i] = true;
                tempList.add(nums[i]);
                DFS(nums, tempList, used);
                used[i] = false;
                tempList.remove(tempList.size() - 1);
                
            }
        }
    }

    参考资料:n/a

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    时间复杂度,空间复杂度
    冒泡排序,选择排序,插入排序
    redis集群
    redis进阶
    redis常识--基础
    mysql基本操作
    TCP/IP 的介绍
    OSI七层网络模型&TCP&UDP&三握四挥
    DNS
    局域网&广域网
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12446555.html
Copyright © 2011-2022 走看看