LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目:

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 + "\t");            System.out.println();        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.