[LeetCode][Java] Permutations II

來源:互聯網
上載者:User

標籤:leetcode   java   permutations ii   

題目:

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,1,2] 擁有下面的這些組合:

[1,1,2], [1,2,1], and [2,1,1].

演算法分析:

這個題跟題目《Permutations》非常類似,唯一的區別就是在這個題目中元素集合可以出現重複。在上一個演算法的基礎上,當我們枚舉第i個位置的元素時,若要把後面第j個元素和i交換,則先要保證[i…j-1]範圍內沒有和位置j相同的元素。可行的做法是:可以每次在需要交換時進行順序尋找。

AC代碼:

<span style="font-size:12px;">public class Solution {public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();permuteUnique(num, 0, result);return result;}private static void permuteUnique(int[] num, int start, ArrayList<ArrayList<Integer>> result) {if (start >= num.length ) {ArrayList<Integer> item = convertArrayToList(num);result.add(item);}for (int j = start; j <= num.length-1; j++) {if (containsDuplicate(num, start, j)) {swap(num, start, j);permuteUnique(num, start + 1, result);swap(num, start, j);}}}private static void swap(int[] a, int i, int j){int temp = a[i];a[i] = a[j];a[j] = temp;}private static ArrayList<Integer> convertArrayToList(int[] num) {ArrayList<Integer> item = new ArrayList<Integer>();for (int h = 0; h < num.length; h++)item.add(num[h]);return item;}private static boolean containsDuplicate(int[] arr, int start, int end) {for (int i = start; i <= end-1; i++) {if (arr[i] == arr[end]) return false;}return true;}}</span>



著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Permutations II

聯繫我們

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