zoukankan      html  css  js  c++  java
  • 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     ArrayList<ArrayList<Integer>> result = null;
     3     int len = 0;
     4     public ArrayList<ArrayList<Integer>> permute(int[] num) {
     5         // Start typing your Java solution below
     6         // DO NOT write main() function
     7         result = new ArrayList<ArrayList<Integer>>();
     8         if(num == null || num.length == 0) return result;
     9         len = num.length;
    10         boolean[] item = new boolean[len];
    11         get(item, num, new ArrayList<Integer>());
    12         return result;
    13     }
    14     public void get(boolean[] item, int[] num, ArrayList<Integer> row){
    15         if(row.size() == len){
    16             result.add(new ArrayList<Integer>(row));
    17             return;
    18         }
    19         for(int i = 0; i < len; i ++){
    20             if(!item[i]){
    21                 item[i] = true;
    22                 row.add(num[i]);
    23                 get(item, num, row);
    24                 item[i] = false;
    25                 row.remove(row.size() - 1);  
    26             }
    27         }
    28     }
    29 }

     第三遍:

     1 public class Solution {
     2     public List<List<Integer>> permute(int[] num) {
     3         ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
     4         getPermutation(num, num.length, new ArrayList<Integer>(), result);
     5         return result;
     6     }
     7     public void getPermutation(int[] num, int len, ArrayList<Integer> row, ArrayList<List<Integer>> result){
     8         if(num == null || len == 0){
     9             result.add(row);
    10             return;
    11         }
    12         for(int i = 0; i < len; i ++){
    13             ArrayList<Integer> nrow = new ArrayList<Integer>(row);
    14             nrow.add(num[i]);
    15             int tmp = num[i];
    16             num[i] = num[len - 1];
    17             getPermutation(num, len - 1, nrow, result);
    18             num[i] = tmp;
    19         }
    20     }
    21 }
  • 相关阅读:
    Codeforces 543E. Listening to Music
    UOJ #138. 【UER #3】开学前的涂鸦
    bzoj 3569: DZY Loves Chinese II
    bzoj 2428: [HAOI2006]均分数据
    bzoj 4589: Hard Nim
    UOJ #119. 【UR #8】决战圆锥曲线
    spoj5973
    codeforces555E
    poj1275
    bzoj4152
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3363076.html
Copyright © 2011-2022 走看看