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

思路分析:Permutation的题目都可以formalize成Search问题来解,当我们把数组排序后,可以从空集开始,不断添加没有使用过的数字形成新的set,直到这个set的长度等于num数组的长度那么就找到了一个Permutation。用DFS搜索解比较直接。但是这题要注意判断重复数字的情况,对于排序后的数组从前向后迭代,重复数字肯定是相邻数字,那么如果当前数字等于前一个相邻数字而前一个数字没有使用,说明添加这个数字到尾部所形成的分支已经在之前搜索过,不必再搜索一次,可以剪掉,直接返回。为了深入理解这个DFS搜索的过程,我画出了针对两个简单输入例子的搜索树。给出了没有重复数字(1 2 3)和有重复数字(1 1 2)针对Permutation的搜索过程。另外,这题还要注意向结果List中添加新的Permutation时要添加拷贝而不是原来的对象引用,否则后面对state的操作会覆盖之前添加的Permutation,这是很容易犯的的错误,要特别小心。

这题的Code也可以适用于没有重复数字的情况 ,也就是LeetCode Permutations问题。



AC Code

public class Solution {
    
    public List<List<Integer>> permuteUnique(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;
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值