Permutations

https://oj.leetcode.com/problems/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].

解题思路:

一道枚举出所有组合的题目,和前面的Letter Combinations of a Phone Number很相似。可以用DFS和BFS两种方法来求解。

所谓DFS,就是带backtracking的递归。BFS则是迭代。这里和电话号码的题目不同的是,一个组合内的号码不能重复。所以在DFS中,用了个visited的数组来记录哪些数字已经出现过。在BFS中,每次看前面的currentList里是否已经有当前数字。

特别要注意,BFS的时候,从resultList里get出来的list不能直接add完再塞进resultList里,因为拿出来的是引用,这样所有的list都指向一个对象了。

public class Solution {

    public List<List<Integer>> permute(int[] num) {

        List<List<Integer>> resultList = new ArrayList<List<Integer>>();

        List<Integer> currentList = new ArrayList<Integer>();

        if(num.length == 0){

            return resultList;

        }

        int[] visited = new int[num.length];

        // dfs(num, visited, resultList, currentList, 0);

        // return resultList;

        return bfs(num);

    }

    

    public List<List<Integer>> bfs(int[] num){

        List<List<Integer>> resultList = new ArrayList<List<Integer>>();

        resultList.add(new ArrayList<Integer>());

        for(int i = 0; i < num.length; i++){

            List<List<Integer>> currentResultList = new ArrayList<List<Integer>>();

            for(int j = 0; j < num.length; j++){

                for(int k = 0; k < resultList.size(); k++){

                    List<Integer> currentList = new ArrayList(resultList.get(k));

                    //不能写成List<Integer> currentList = resultList.get(k)

                    //否则对currentList的更改也都影响resultList前面的值,非常重要!!!

                    if(!currentList.contains(num[j])){

                        currentList.add(num[j]);

                        currentResultList.add(currentList);

                    }

                }

            }

            resultList = currentResultList;

        }

        return resultList;

    }

    

    public void dfs(int[] num, int[] visited, List<List<Integer>> resultList, List<Integer> currentList, int depth){

        if(currentList.size() == num.length){

            resultList.add(new ArrayList(currentList));

            return;

        }

        for(int i = 0; i < num.length; i++){

            if(visited[i] == 0){

                currentList.add(num[i]);

                visited[i] = 1;

                dfs(num, visited, resultList, currentList, depth + 1);

                currentList.remove(currentList.size() - 1);

                visited[i] = 0;

            }

        }

    }

}

 http://blog.csdn.net/linhuanmars/article/details/21569031

你可能感兴趣的:(IO)