Permutation II @leetcode

 转自:http://www.cnblogs.com/longhorn/p/3527824.html


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

有重复数字的话,用递归就不是很好做。每一次产生一个结果就要判断这个结果是否已经包含在result中,所以时间长。

用dfs做的话用两个地方需要注意。

一个是要对字符串进行排序。因为如果排序的话,可以很好避免因为重复数字产生的重复的情况。

第二个就是如何避免因为重复数字产生的重复情况。因为已经排好序,所以每次选择下一个数字的时候只要避免和之前的数字重复就行。

比如[1,2,3,3,4].当我们产生[1,2,3]的时候,我们只要避免回溯的时候再次选择3,从而产生[1,2,3]就行了。


public class Solution {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        Arrays.sort(num);
        boolean[] visited = new boolean[num.length];
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        permute2(num, visited, tmp, result);
        return result;
    }
    
    public static void permute2(int[] num, boolean[] visited, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> result) {
        if (tmp.size() == num.length) {
            result.add(new ArrayList<Integer>(tmp));
            return;
        }
        for (int i=0; i<num.length; i++) {
            if (visited[i] == false) {
                tmp.add(num[i]);
                visited[i] = true;
                permute2(num, visited, tmp, result);
                visited[i] = false;
                tmp.remove(tmp.size()-1);
              <span style="background-color: rgb(255, 0, 0);">  while (i<num.length-1 && num[i] == num[i+1]) i++;</span>
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值