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();
            }
        }
    
    }
  • 相关阅读:
    爬取淘宝商品信息
    eclipse 搭建Robotium环境--apk 环境搭建
    android studio2.0 搭建Robotium环境--有被测源代码的情况下
    mysql 特殊语句
    电脑浏览器访问文件夹
    mindmanager 15 停止工作
    yum被lock Existing lock /var/run/yum.pid: another copy is running as pid 1580. Another app is currently holding the yum lock; waiting for it to exi
    jenkins安装及部署
    ant+jmeter
    charles抓包及篡改
  • 原文地址:https://www.cnblogs.com/null00/p/5075712.html
Copyright © 2011-2022 走看看