zoukankan      html  css  js  c++  java
  • leetcode47

     1 public class Solution {
     2     public List<List<Integer>> permuteUnique(int[] nums) {
     3         List<List<Integer>> permutes = new ArrayList<>();
     4         List<Integer> permuteList = new ArrayList<>();
     5         Arrays.sort(nums);  // 排序
     6         boolean[] hasVisited = new boolean[nums.length];
     7         backtracking(permuteList, permutes, hasVisited, nums);
     8         return permutes;
     9     }
    10 
    11     private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
    12         if (permuteList.size() == nums.length) {
    13             permutes.add(new ArrayList<>(permuteList));
    14             return;
    15         }
    16 
    17         for (int i = 0; i < visited.length; i++) {
    18             if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
    19                 continue;  // 防止重复
    20             }
    21             if (visited[i]){
    22                 continue;
    23             }
    24             visited[i] = true;
    25             permuteList.add(nums[i]);
    26             backtracking(permuteList, permutes, visited, nums);
    27             permuteList.remove(permuteList.size() - 1);
    28             visited[i] = false;
    29         }
    30     }
    31 }

    对比leetcode46

     1 public class LEET_46 {
     2     public List<List<Integer>> permute(int[] nums) {
     3         List<List<Integer>> permutes = new ArrayList<>();
     4         List<Integer> permuteList = new ArrayList<>();
     5         boolean[] hasVisited = new boolean[nums.length];
     6         backtracking(permuteList, permutes, hasVisited, nums);
     7         return permutes;
     8     }
     9 
    10     private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
    11         if (permuteList.size() == nums.length) {
    12             permutes.add(new ArrayList<>(permuteList)); // 重新构造一个 List
    13             return;
    14         }
    15         for (int i = 0; i < visited.length; i++) {
    16             if (visited[i]) {
    17                 continue;
    18             }
    19             visited[i] = true;
    20             permuteList.add(nums[i]);
    21             backtracking(permuteList, permutes, visited, nums);
    22             permuteList.remove(permuteList.size() - 1);
    23             visited[i] = false;
    24         }
    25     }
    26 }
  • 相关阅读:
    Linux: 安装和启用firefox浏览器的java
    Latex: beamer
    时频分析:窗口傅立叶变换
    Python: 面向对象
    Linux: 安装NVIDIA显卡驱动
    Matlab: 路径的操作
    python--文件读写
    python--函数
    python--数据类型
    网络基础——网络协议
  • 原文地址:https://www.cnblogs.com/asenyang/p/10997891.html
Copyright © 2011-2022 走看看