【LeetCode】Permutations II 解題報告,permutationsii

來源:互聯網
上載者:User

【LeetCode】Permutations II 解題報告,permutationsii

【題目】

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].

【解析】

題意:求一個數組的全排列,與【LeetCode】Permutations 解題報告 不同的是,數組中的數有重複。

對於全排列,現在比較常用的演算法就是根據 【LeetCode】Next Permutation 解題報告 從小到大逐個找出所有的排列。

演算法:回溯、字典序法。

public class Solution {    List<List<Integer>> ans = new ArrayList<List<Integer>>();        public List<List<Integer>> permuteUnique(int[] num) {        Arrays.sort(num);                //首先得把原始數組添加到結果集        List<Integer> list = new ArrayList<Integer>();        for (int x : num) {            list.add(x);        }        ans.add(list);                //逐個添加下一個解        for (int i = 1; i < factorial(num.length); i++) {            nextPermutation(num);        }                return ans;    }        public void nextPermutation(int[] num) {        //找到最後一個正序        int i = num.length - 1;        while (i > 0 && num[i] <= num[i - 1]) {            i--;        }        if (i <= 0) return;                //找到最後一個比num[i-1]大的數        int j = num.length - 1;        while (j >= i && num[j] <= num[i - 1]) {            j--;        }                //交換        int tmp = num[i - 1];        num[i - 1] = num[j];        num[j] = tmp;                //逆排i-1之後的數        int l = i, r = num.length - 1;        while (l < r) {            tmp = num[l];            num[l] = num[r];            num[r] = tmp;            l++;            r--;        }                //添加到結果集        List<Integer> list = new ArrayList<Integer>();        for (int x : num) {            list.add(x);        }        ans.add(list);    }        public int factorial(int n) {        return n == 0 ? 1 : n * factorial(n - 1);    }}


相關題目:【LeetCode】Permutations 解題報告 和 【LeetCode】Next Permutation 解題報告 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.