Permutations II, Leetcode 解题笔记

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


public class Solution {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        Arrays.sort(num); //这里不要忘了先排序
        int[] visited = new int[num.length];
        dfs(ret, sol, num, visited, 0);
        return ret;
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int[] num, int[] visited, int deep){
        if(deep == num.length){
            ret.add(new ArrayList<Integer>(sol));
        for(int i = 0; i < num.length; i++){
            if(visited[i] == 0){
                visited[i] = 1;
                dfs(ret, sol, num, visited, deep+1);
                visited[i] = 0;
                while(i < num.length-1 && num[i+1] == num[i]) i++; //如果当前数字与前一个重复,直接跳过

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s