zoukankan      html  css  js  c++  java
  • 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].

    思路:

    1) 直接利用permutation的代码,可以利用list.contains(o)的方法来去除重复【returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

    2) 和Permutation一样,排序之后,不断的见缝插针,遇到重复时,只在这个这个值的前面插入,然后就break,为什么呢?因为已经形成的集合具有对称性,所以我们就只在重复值的左边插入。当然,你也可以只在重复值的右边插入。

    package permutation;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class PermutationsII {
    
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            Arrays.sort(nums);
            List<Integer> subRes = new ArrayList<Integer>();
            subRes.add(nums[0]);
            res.add(subRes);
            return permute(res, nums, 1);
        }
        
        private List<List<Integer>> permute(List<List<Integer>> res, int[] nums, int pos) {
            if (pos >= nums.length) return res;
            List<List<Integer>> newRes = new ArrayList<List<Integer>>();
            for (List<Integer> subRes : res) {
                int count = subRes.size();
                for (int i = 0; i <= count; ++i) {
                    if (i > 0 && nums[pos] == subRes.get(i - 1))
                        break;
                    List<Integer> newSubRes = new ArrayList<Integer>(subRes);
                    newSubRes.add(i, nums[pos]);
                    newRes.add(newSubRes);
                }
            }
            return permute(newRes, nums, pos + 1);
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            PermutationsII p = new PermutationsII();
            int[] nums = { 2,2,1,1 };
            List<List<Integer>> res = p.permuteUnique(nums);
            for (List<Integer> l : res) {
                for (int i : l)
                    System.out.print(i + "	");
                System.out.println();
            }
        }
    
    }
  • 相关阅读:
    python 全栈开发,Day127(app端内容播放,web端的玩具,app通过websocket远程遥控玩具播放内容,玩具管理页面)
    队列Queue FIFO先进先出 栈Stack FILO先进后出
    sql server 2008 学习笔记
    c#剪切板
    c#复制图片到粘贴板
    C# GUID的使用
    winform自定义控件
    进程和线程
    vs常用快捷键
    c# foreach循环二维数组
  • 原文地址:https://www.cnblogs.com/null00/p/5075712.html
Copyright © 2011-2022 走看看