47. 全排列 II-bfs/回溯-中等难度

问题描述

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii

解答

class Solution {
    public void backtrack(int n, List<Integer> temp, List<List<Integer>> res, int first){
        if(first == n)res.add(new ArrayList<Integer>(temp));
        for(int i=first;i<n;i++){
            Collections.swap(temp,i,first);
            if(!res.contains(temp))backtrack(n, temp, res, first+1);
            Collections.swap(temp,first,i);
        }
    }
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        for(int i:nums)
            temp.add(i);
        System.out.println(temp);
        backtrack(temp.size(), temp, res, 0);
        return res;
    }
}
原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13339576.html