• Permutations II


    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2][1,2,1], and [2,1,1].

     1 public class Solution {
     2      public List<List<Integer>> permuteUnique(int[] num) {
     3          List<List<Integer>> result = new ArrayList<List<Integer>>();
     4          List<Integer> curr = new ArrayList<Integer>();
     5          Arrays.sort(num);
     6          dfs(result, curr, num, 0);
     7          return result;
     8      }
     9 
    10      void dfs(List<List<Integer>> result, List<Integer> curr, int[] num, int index) {
    11          if (index == num.length) {
    12              if (!result.contains(curr)) {
    13                 result.add(new ArrayList<Integer>(curr));
    14 
    15              }
    16          } else {
    17              for (int i = index; i <num.length ; i++) {
    18                  if (noSwap(num,i,index)) {
    19                      continue;
    20                  } else {
    21                      swap(num, i, index);
    22                  }
    23                  curr.add(num[index]);
    24                  dfs(result, curr, num, index + 1);
    25                  curr.remove(curr.size() - 1);
    26                  swap(num, index,i );
    27 
    28              }
    29 
    30          }
    31      }
    32 
    33      void swap(int[] num, int indexA, int indexB) {
    34          int temp = num[indexA];
    35          num[indexA] = num[indexB];
    36          num[indexB] = temp;
    37      }
    38 
    39      boolean noSwap(int[] num, int i, int j) {
    40          for (int k = j; k < i; k++) {
    41              if (num[k] == num[i]) {
    42                  return true;
    43              }
    44          }
    45          return false;
    46      }
    47 
    48 }
  • 相关阅读:
    python笔记1
    git笔记
    手撸一个简陋直播系统
    spring-boot学习笔记1
    设计模式1--简单工厂模式
    网联:第一章:浏览器生成消息
    php线上预览日志--4.websocket客户端
    php线上预览日志--3.websocket服务部署
    php线上预览日志--2.谷歌插件开发
    php线上预览日志--1.概述
  • 原文地址:https://www.cnblogs.com/birdhack/p/4280680.html
Copyright © 2020-2023  润新知