zoukankan      html  css  js  c++  java
  • leecode 排列的学习

    前面写过3个排列。这里再写一次。

    1.全部都不重复https://oj.leetcode.com/problems/permutations/

    (使用交换法)只是本人对c++ stl不熟,不会把排列结果保存,这里用java写一遍。

     1 public class Solution {
     2     public List<List<Integer>> permute(int[] num) {
     3         
     4        
     5        ArrayList<ArrayList<Integer>> total=new    ArrayList<ArrayList<Integer>>();
     6      
     7         if(num.length==0) return (List)total;
     8        int lev=0;
     9        per(total,num,lev);
    10         return  (List)total;
    11         
    12     }
    13     public void swap(int num[],int i,int j)
    14     {
    15         int temp=num[i];
    16         num[i]=num[j];
    17         num[j]=temp;
    18         
    19     }
    20     
    21     public void per(ArrayList<ArrayList<Integer>> total,int num[],int lev)
    22     {
    23         if(lev==num.length)
    24         {
    25             ArrayList ar=new ArrayList<Integer>();
    26             for(int i=0;i<num.length;i++)
    27             {
    28                 ar.add(num[i]);
    29             }
    30             total.add(ar);
    31 
    32         }
    33         else
    34         {
    35             for(int i=lev;i<num.length;i++)
    36             {
    37                 swap(num,lev,i);
    38                
    39                 per(total,num,lev+1);
    40                 swap(num,lev,i);
    41                 
    42                 
    43             }
    44             
    45             
    46         }
    47         
    48         
    49     }
    50 }

    2.

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

    思路就是 假设当前考虑的是第一位的2 ,只有第一个1需要交换,因为 1 21 和1 12 对于,21和12排列都向等,所以,在前文的基础上加上一个过滤的交换条件就行

  • 相关阅读:
    【转】千万别理程序员
    qemu-ifup and qemu-ifdown
    Fedora-23 installation in VM image
    Set up bridge to connect to internet
    fedora25 上设置br0
    助教工作总结
    树1
    线性结构
    链表基本操作
    自定义函数
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3823009.html
Copyright © 2011-2022 走看看