Link: https://oj.leetcode.com/problems/permutations/
Time: O(n!)
Approach I: Recursive(DFS)
public class Solution {
//Recursive
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num == null || num.length == 0) return result;
boolean[] used = new boolean[num.length];
helper(num, used, new ArrayList<Integer>(), result);
return result;
}
public void helper(int[] num, boolean[] used, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> result){
//Only add an item into result when the item has added all elements in the "num" array
if(item.size() == num.length){
result.add(new ArrayList<Integer>(item));//note: we cannot use result.add(item)
return;
}
for(int i = 0; i < num.length; i++){
if(!used[i]){
used[i] = true;
item.add(num[i]);
helper(num, used, item, result);
item.remove(item.size()-1);//backtrack
used[i] = false;
}
}
}
}
Note: We cannot use result.add(item) in helper function. It will cause "Wrong Answer":
Input:[1]
Output:[[]]
Expected:[[1]]
I supposed its because "item" is passed by reference. So when item.remove(item.size()-1) is excecuted, the item in result will change correspondingly. So we need to make a deep copy when adding "item" into result.
Approach II: Iterative
public class Solution {
//iterative. why no backtrack?
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num == null || num.length == 0) return result;
ArrayList<Integer> first = new ArrayList<Integer>();
first.add(num[0]);
result.add(first);
for(int i = 1; i < num.length; i++){
//result for the i-th level?
ArrayList<ArrayList<Integer>> nRes = new ArrayList<ArrayList<Integer>>();
for(int j = 0; j < result.size(); j++){
ArrayList<Integer> cur = result.get(j);
//insert the current array element num[i]
for(int k = 0; k < cur.size()+1; k++){
ArrayList<Integer> item = new ArrayList<Integer>(cur);
item.add(k, num[i]);
nRes.add(item);
}
}
result = nRes;
}
return result;
}
}
Approach II: Iterative by Next Permutation (STL in C++)
Code is referred from http://blog.csdn.net/u013027996/article/details/18734103 (See my leetcode)
Good explanation of the algorithm:
http://blog.csdn.net/morewindows/article/details/7370155