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].

    Solution:

     1 public class Solution {
     2     public List<List<Integer>> permuteUnique(int[] num) {
     3         Arrays.sort(num);
     4         List<List<Integer>> result=new ArrayList<List<Integer>>();
     5         List<Integer> al=new ArrayList<Integer>();
     6         boolean[] flag=new boolean[num.length];
     7         dfs(num,result,al,0,flag);
     8         return result;
     9     }
    10 
    11     private void dfs(int[] num, List<List<Integer>> result, List<Integer> al, int level,boolean[] flag) {
    12         // TODO Auto-generated method stub
    13         if(level>num.length)
    14             return;
    15         if(level==num.length){
    16             result.add(new ArrayList<Integer>(al));
    17             return;
    18         }
    19         for(int i=0;i<num.length;++i){
    20             if(!flag[i]){
    21                 flag[i]=true;
    22                 al.add(num[i]);
    23                 dfs(num, result, al, level+1, flag);
    24                 al.remove(al.size()-1);
    25                 flag[i]=false;
    26                 while((i+1<num.length)&&num[i]==num[i+1])
    27                     ++i;
    28             }
    29         }    
    30     }
    31 }
  • 相关阅读:
    FTP与HTTP上传文件的对比
    【FTP】Wireshark学习FTP流程
    【CSS】div
    浏览器URL中“#” “?” &“”作用
    【EF】vs2017中没有EF模型
    C# List的使用
    C# Dictionary使用
    Git/GitHub的一些问题
    PHP中的break与continue
    css使文字垂直水平居中
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4093981.html
Copyright © 2011-2022 走看看