Permutations, Leetcode 解题笔记

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

标准DFS递归解法,现在感觉越来越熟练了,注意在递归中要记录哪些数字已经被使用过,以免重复。

public class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        int[] visited = new int[num.length];
        dfs(ret, sol, num, visited, 0);
        return ret;
    }
    
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int[] num, int[] visited, int deep){
        if(deep == num.length){
            ret.add(new ArrayList<Integer>(sol));
            return;
        }
        for(int i = 0; i < num.length; i++){
            if(visited[i] == 0){
                visited[i] = 1;
                sol.add(num[i]);
                dfs(ret, sol, num, visited, deep+1);
                sol.remove(sol.size()-1);
                visited[i] = 0;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s