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/

  • 相关阅读:
    替换TStrings
    WordPress数据备份方案
    图像反色
    通过网络复制文件
    SQL Server的patindex和charindex的用法
    C冒泡排序 @100到200素数
    正则。IP验证
    C以二进制读、写、文本
    HTML下拉框、文本框、复选框!
    HTM页面获得本机时间
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12446555.html
Copyright © 2011-2022 走看看