zoukankan      html  css  js  c++  java
  • Leetcode-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].

    Have you met this question in a real interview?
     
    Analysis:
    We sort the array first, then we use recursive method to construct the solution. At each position, it will place each current available number on it. For handling duplicates, if we have already put a num X on the current place, we then skip all X in the following iterations.
     
    Solution:
     1 public class Solution {
     2     public List<List<Integer>> permuteUnique(int[] num) {
     3         boolean[] used = new boolean[num.length];
     4         Arrays.fill(used,false);
     5         Arrays.sort(num);
     6         List<List<Integer>> resSet = new ArrayList<List<Integer>>();
     7         List<Integer> curStr = new ArrayList<Integer>();
     8         permuteRecur(num,used,0,curStr,resSet);
     9         return resSet;        
    10     }
    11 
    12     public void permuteRecur(int[] num, boolean[] used, int cur, List<Integer> curStr, List<List<Integer>> resSet){
    13         if (cur==num.length){
    14             List<Integer> res = new ArrayList<Integer>();
    15             res.addAll(curStr);
    16             resSet.add(res);
    17             return;
    18         }
    19 
    20         boolean init = true;
    21         int lastVal = -1;
    22         for (int i=0;i<num.length;i++)
    23             if (used[i] || (!init && num[i]==lastVal))
    24                 continue;
    25             else {
    26                 init = false;
    27                 curStr.add(num[i]);
    28                 used[i]=true;
    29                 permuteRecur(num,used,cur+1,curStr,resSet);
    30                 used[i]=false;
    31                 curStr.remove(curStr.size()-1);
    32                 lastVal = num[i];
    33             }
    34     }
    35 }
  • 相关阅读:
    JAVA GUI设
    3.4 jmu-java-随机数-使用蒙特卡罗法计算圆周率的值 (10 分)
    问题:关于2.3 jmu-Java-02基本语法-03-身份证排序 (9 分)
    关于3.1 jmu-Java-03面向对象基础-01-构造函数与toString (3 分)
    linux vim文件编辑的常用命令
    linux的常用命令
    linux文件存储方式
    第一个java
    hdu 2795
    hdu 1394
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4110294.html
Copyright © 2011-2022 走看看