• LeetCode Permutations


    Given a collection of numbers, return all possible permutations.

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

    采用递归的思路,一次加一个数,每次更新上一次的结果。

     1 public class Solution {
     2 
     3     public List<List<Integer>> permute(int[] num) {
     4         List<List<Integer>> lastList=new ArrayList<List<Integer>>();
     5         List<List<Integer>> currList=new ArrayList<List<Integer>>();
     6             if (num==null) {
     7                 return lastList;
     8             }
     9             
    10             List<Integer> eleList=new ArrayList<>();
    11             eleList.add(num[0]);
    12             lastList.add(eleList);
    13             
    14             if (num.length==1) {
    15                 return lastList;
    16             }
    17             for (int i = 1; i < num.length; i++) {
    18                 for (List<Integer> l : lastList) {
    19                     currList.addAll(insertList(num[i], l));
    20                     
    21                 }
    22                 lastList.clear();
    23                 lastList.addAll(currList);
    24                 currList.clear();
    25         }
    26             return lastList;
    27             
    28     }
    29     
    30     private List<List<Integer>> insertList(int num,List<Integer> list) {
    31             List<List<Integer>> retNew=new ArrayList<List<Integer>>();
    32             
    33             for (int i = 0; i <= list.size(); i++) {
    34                     List<Integer> currlist=new ArrayList<>();
    35                 currlist.addAll(list);
    36                 currlist.add(i, num);
    37                 retNew.add(currlist);
    38                 currlist=null;
    39             }
    40             return retNew;
    41         
    42     }
    43 }
  • 相关阅读:
    2020.11.17
    2020.11.26
    2020.11.18
    2020.12.01
    2020.11.23
    Java编程规范
    20201003 千锤百炼软工人
    2020081920200825 千锤百炼软工人
    20201004 千锤百炼软工人
    20200929 动手动脑
  • 原文地址:https://www.cnblogs.com/birdhack/p/4032287.html
Copyright © 2020-2023  润新知