首页 > 代码库 > LeetCode Permutations

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

思路分析:这题是Permutations II问题的简化版本,直接用DFS搜索做,不必判断重复数字的情况。详细题解分析可以参考 LeetCode Permutations II

AC Code

public class Solution {
    
    public List<List<Integer>> permute(int[] num) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(num == null || num.length == 0){
            return res;
        }
        Arrays.sort(num);
        List<Integer> state = new ArrayList<Integer>();
        dfs(res, state, num, new boolean[num.length]);
        return res;
    }
    
    void dfs(List<List<Integer>> res, List<Integer> state, int [] num, boolean [] used){
        if(state.size() == num.length){
            res.add(new ArrayList(state));//add a copy
            return;
        } 
        for(int i = 0; i < num.length; i++){
            //if(i > 0 && !used[i-1] && num[i] == num[i-1]) continue;// judge duplicate number
            if(!used[i]){
                state.add(num[i]);
                used[i] = true;
                dfs(res, state, num, used);
                state.remove(state.size() - 1);
                used[i] = false;
            }
        }
    }
}


LeetCode Permutations