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

    Analysis:

    The idea of this classic problem is to use backtracking.
    We want to get permutations, which is mainly about swap values in the list.
    Consider:
    a --> a
    ab --> ab, ba
    abc --> abc, acb, bac, bca, cab, cba.
    ...
    where for the length of n, the permutations can be generated by
    (1) Swap the 1st element with all the elements, including itself.
           (2) Then the 1st element is fixed, go to the next element.
           (3) Until the last element is fixed. Output.
    It's more clear in the figure above. The key point is to make the big problem into smaller problem, here is how to convert the length n permutation into length n-1 permutation problem.

    public class Solution {
        
        public ArrayList<ArrayList<Integer>> permute(int[] num){
           ArrayList<ArrayList<Integer>> result = new  ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> output = new ArrayList<Integer>();
            boolean[] visited = new boolean[num.length];
           getPermutation(0, num, output, result, visited);
           return result;
        }
        
        private void getPermutation(int depth, int[] num, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> result, boolean[] visited){
            if(depth == num.length){
                 ArrayList<Integer> tmp = new ArrayList<Integer>();
                 tmp.addAll(output);
                 result.add(tmp);
            }
            
            for(int i= 0 ; i< num.length; i++){
                if(visited[i])
                    continue;
                visited[i] = true;
                output.add(num[i]);
                getPermutation(depth+1, num, output, result, visited);
                output.remove(output.size() -1);
                 visited[i] = false;
            }
            
        }
    }
  • 相关阅读:
    UVA12206 Stammering Aliens 【SAM 或 二分 + hash】
    字符串hash
    BZOJ1064 [Noi2008]假面舞会 【dfs】
    BZOJ2333 [SCOI2011]棘手的操作 【离线 + 线段树】
    BZOJ1499 [NOI2005]瑰丽华尔兹 【单调队列优化dp】
    BZOJ3343 & 洛谷2801:教主的魔法——题解
    BZOJ2821:作诗——题解
    BZOJ2724:[Violet 6]蒲公英——题解
    BZOJ2653:middle——题解
    BZOJ2588:Count on a tree——题解
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3536039.html
Copyright © 2011-2022 走看看