码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Permutations

时间:2014-11-23 13:07:51      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

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

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://blog.csdn.net/yangliuy/article/details/41409991

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!