Last active
December 14, 2015 05:40
-
-
Save daifu/5036888 to your computer and use it in GitHub Desktop.
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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]. | |
| */ | |
| public class Solution { | |
| public boolean[] used; | |
| public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); | |
| ArrayList<Integer> list = new ArrayList<Integer>(); | |
| if (num.length == 0) return results; | |
| used = new boolean[num.length]; | |
| Arrays.sort(num); | |
| permute(num, list, results); | |
| return results; | |
| } | |
| public void permute(int[] num, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> results) { | |
| if (num.length == list.size()) { | |
| results.add(new ArrayList<Integer>(list)); | |
| return; | |
| } | |
| for(int i = 0; i < num.length; i++) { | |
| if ((used[i]) || (i != 0 && num[i] == num[i-1] && used[i-1])) continue; | |
| // try | |
| list.add(num[i]); | |
| used[i] = true; | |
| // next | |
| permute(num, list, results); | |
| // rework | |
| list.remove(list.size() - 1); | |
| used[i] = false; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment