zoukankan      html  css  js  c++  java
  • [LintCode] Permutations

    Given a list of numbers, return all possible permutations.

    You can assume that there is no duplicate numbers in the list.

    Example

    For nums = [1,2,3], the permutations are:

    [
      [1,2,3],
      [1,3,2],
      [2,1,3],
      [2,3,1],
      [3,1,2],
      [3,2,1]
    ]
    
    Challenge 

    Do it without recursion.

    Solution 1. Recursion

    Highlighted line 21 decides at each level, which element should be picked first. Take [1,2,3] as an example, we know all permutations must start with 1, 2, or 3.

    used flag ensures that we do not pick the same element more than once.

     1 public class Solution {
     2     public List<List<Integer>> permute(int[] nums) {
     3         List<List<Integer>> results = new ArrayList<>();
     4         if(nums == null || nums.length == 0) {
     5             results.add(new ArrayList<Integer>());
     6             return results;
     7         }
     8         boolean[] used = new boolean[nums.length];
     9         for(int i = 0; i < used.length; i++) {
    10             used[i] = false;
    11         }
    12         permuteDfs(results, new ArrayList<Integer>(), nums, used);
    13         return results;
    14     }
    15     private void permuteDfs(List<List<Integer>> results, List<Integer> list, 
    16                             int[] nums, boolean[] used) {
    17         if(list.size() == nums.length) {
    18             results.add(new ArrayList<Integer>(list));
    19             return;
    20         }
    21         for(int i = 0; i < nums.length; i++) {
    22             if(used[i]) {
    23                 continue;
    24             }
    25             list.add(nums[i]);
    26             used[i] = true;
    27             permuteDfs(results, list, nums, used);
    28             list.remove(list.size() - 1);
    29             used[i] = false;
    30         }
    31     }
    32 }

    Solution 2. Iteration

    Related Problems

    Print Numbers By Recursion

    Permutation Sequence

    Permutations II

  • 相关阅读:
    mysql6.0免安装配置
    SQL2005安装时“性能监视器计数器要求(错误)”解决办法
    Centos 下解压和压缩rar文件
    MyEclipse插件介绍与下载
    算法设计之递归法
    Centos5.2 下安装MySQL+Tomcat6 及设置自启动
    科学用电脑
    浅谈Linux的安全设置
    JAVA程序员之路
    CentOS 5.5 挂载Windows NTFS 文件系统
  • 原文地址:https://www.cnblogs.com/lz87/p/7494145.html
Copyright © 2011-2022 走看看