首页 > 其他 > 详细

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

时间:2020-07-19 17:22:30      阅读:73      评论:0      收藏:0      [点我收藏+]

问题描述

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

示例:

输入: [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;
    }
}

 

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

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13339576.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!