[LeetCode-JAVA] Permutations II

题目:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

题意:和I一样,找到所有的排列数 唯一不同的是 数组中会有重复的数字

思路:加入visited判断该位置是否被选择了,避免选到自身,但这样还是会TLE,这时需要最关键的一步,开始dfs前对nums排序,这样,在dfs的时候 如果nums[i] == nums[i-1] 并且 visited[i-1] ==false的话 就continue,试想一下,这时的数字和前一个是一样的,前一个都没有被visited到,证明以这个数的排列已经完成了 那这个数字肯定是不用的了。

代码:

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if(nums == null || nums.length == 0)
            return list;
            
        List<Integer> temp = new ArrayList<Integer>();
        boolean[] visited = new boolean[nums.length];
        
        Arrays.sort(nums);   // 关键1
        dfs(list, temp, nums, visited, 0);
        return list;
    }
    
    public void dfs(List<List<Integer>> list, List<Integer> temp, int[] nums, boolean[] visited, int count) {
        if(count == nums.length) {
            if(!list.contains(temp))
                list.add(new ArrayList<Integer>(temp));
            return;
        }
        
        for(int i = 0 ; i < nums.length ; i++) {
            if(i > 0 && nums[i-1] == nums[i] && !visited[i-1]) //关键2
                continue;
            if(visited[i])
                continue;
            visited[i] = true;
            temp.add(nums[i]);
            dfs(list, temp, nums, visited, count+1);
            temp.remove(temp.size()-1);
            visited[i] = false;
        }
    }
}

 

posted @ 2015-08-04 20:28  可爱的波儿胖  阅读(158)  评论(0编辑  收藏  举报

友情链接 : CodeForge源码分享