Created
February 28, 2014 22:48
-
-
Save rayjcwu/9281673 to your computer and use it in GitHub Desktop.
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
| public class Solution { | |
| public ArrayList<ArrayList<Integer>> permute(int[] num) { | |
| ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); | |
| final int N = num.length; | |
| if (N > 0) { | |
| perm(num, N, 0, ans); | |
| } | |
| return ans; | |
| } | |
| private boolean containsDuplicate(int []num, int start, int end) { | |
| for (int i = start; i < end; i++) { | |
| if (num[i] == num[end]) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| public void perm(int []num, int N, int i, ArrayList<ArrayList<Integer>> ans) { | |
| if (i == N) { | |
| ArrayList<Integer> t = new ArrayList<Integer>(); | |
| for (int n: num) { | |
| t.add(n); | |
| } | |
| ans.add(t); | |
| } else { | |
| for (int j = i; j < N; j++) { | |
| if (containsDuplicate(num, i, j)) { | |
| continue; | |
| } | |
| swap(num, i, j); | |
| perm(num, N, i + 1, ans); | |
| swap(num, i, j); | |
| } | |
| } | |
| } | |
| private void swap(int []num, int i, int j) { | |
| int t = num[i]; | |
| num[i] = num[j]; | |
| num[j] = t; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment