Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created February 28, 2014 22:48
Show Gist options
  • Select an option

  • Save rayjcwu/9281673 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9281673 to your computer and use it in GitHub Desktop.
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