[LeetCode] Permutations
/**
Solution 1, using recursion.
Construct a list of numbers by maintaining what you have now and what is left.
Every level you take one element from the current "rest" array and append it to "cur"
**/
public class Solution {
public List<List<Integer>> permute(int[] num) {
ArrayList<Integer> rest = new ArrayList<Integer>();
for(int integer: num) {
rest.add(integer);
}
ArrayList<Integer> cur = new ArrayList<Integer>();
ArrayList all = new ArrayList();
permuteHelper(rest,cur,all);
return all;
}
public void permuteHelper(ArrayList<Integer> rest, List cur, List all) {
if(rest.size()==0){
all.add(cur);
return;
}
for(Integer integer : rest) {
cur.add(new Integer(integer));
ArrayList<Integer> temp = new ArrayList<Integer>(rest);
temp.remove(integer);
permuteHelper(temp, new ArrayList<Integer>(cur), all);
cur.remove(integer);
}
}
}
/**
Solution 2
Using a swap function. every level you swap the current index with one of the element on you right you increment current index by one.
**/
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (num == null || num.length == 0) {
return ans;
}
permute(num, 0, ans);
return ans;
}
//helper function
private void permute(int[] num, int index, List<List<Integer>> ans) {
if (index == num.length) {
List<Integer> one = new ArrayList<Integer>();
for (int i : num) {
one.add(i);
}
ans.add(one);
} else {
for (int i = index; i < num.length; ++i) {
swap(num, index, i);
permute(num, index+1, ans);
swap(num, index, i); //swap it back
}
}
}
private void swap(int[] num, int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
如果有duplicate的话
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 List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (num == null || num.length == 0) {
return ans;
}
permuteUnique(num, 0, ans);
return ans;
}
private void permuteUnique(int[] num, int index, List<List<Integer>> ans) {
if (index == num.length) {
List<Integer> one = new ArrayList<Integer>();
for (int i : num) {
one.add(i);
}
ans.add(one);
} else {
for (int i = index; i < num.length; ++i) {
//if the current number has alreay been permuted
//"already seen in this round"
if (!containsDups(num, index, i)) {
swap(num, index, i);
permuteUnique(num, index+1, ans);
swap(num, index, i);
}
}
}
}
private boolean containsDups(int[] num, int start, int end) {
for (int i = start; i < end; ++i) {
if (num[i] == num[end]) {
return true;
}
}
return false;
}
private void swap(int[] num, int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}