zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    什么是 HTTPS
    首页飘雪的效果
    load data导入数据之csv的用法
    phpcms v9 配置sphinx全文索引教程
    js的一些技巧总结
    MySQL 清除表空间碎片
    使用的前台开发在线工具
    (phpQuery)对网站产品信息采集代码的优化
    永远不要打探别人工资
    git 显示多个url地址推送
  • 原文地址:https://www.cnblogs.com/birdhack/p/4032287.html
Copyright © 2011-2022 走看看