Permutations II(带重复元素的排列)

http://www.lintcode.com/zh-cn/problem/permutations-ii/?rand=true

public class Solution {
    /*
     * @param nums: A list of integers.
     *
     * @return: A list of permutations.
     */
    public List> permuteUnique(int[] nums) {
        // write your code here
        List> res = new ArrayList<>();
        if (nums == null) {
            return res;
        }
        if (nums.length == 0) {
            res.add(new ArrayList());
            return res;
        }
        Arrays.sort(nums);
        boolean[] visited = new boolean[nums.length];
        tree(nums, res, new ArrayList<>(), visited);
        return res;
    }

    private void tree(int[] nums, List> res, ArrayList arrayList, boolean[] visited) {
        if (arrayList.size() == nums.length) {
            res.add(new ArrayList(arrayList));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) {
//                访问过了,跳过
                continue;
            }
            if (i != 0 && visited[i - 1] && nums[i] == nums[i - 1]) {
//                和前边的值相等,并且前边的访问过了,跳过
                continue;
            }
            visited[i] = true;
            arrayList.add(nums[i]);
            tree(nums, res, arrayList, visited);
            arrayList.remove(arrayList.size() - 1);
            visited[i] = false;
        }
    }
}

你可能感兴趣的:(Permutations II(带重复元素的排列))