Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
Update 15/01/2014:
Analysis: DFS. Note that for adding the permutations stored in tem each time, deep clone is needed. (ArrayList<Integer> clone = new ArrayList<Integer>(tem);)
public class Solution {
public void permute(int[] num, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tem) {
if(num.length == 0) {
ArrayList<Integer> clone = new ArrayList<Integer>(tem);
res.add(clone);
return;
}
for(int i=0; i<num.length; i++) {
int[] nextNum = new int[num.length-1];
int nextLen = 0;
for(int j=0; j<num.length; j++) {
if(j!=i) nextNum[nextLen++]=num[j];
}
tem.add(num[i]);
permute(nextNum, res, tem);
tem.remove(tem.size()-1);
}
return;
}
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tem = new ArrayList<Integer>();
permute(num, res, tem);
return res;
}
}
Analysis:
1. Recursively, shrinking the given array one element each time until it only has one element. Start with such array by returning its single element to its caller function.
2. For an arbitrary result returned by the last level computation, it must contain all kinds of permutations generated by a range which contains from the first element to the element just before the current one. So, by inserting the current element into all possible positions of all existing permutations returned by the last level computation, we can get all kinds of permutations for the current level.
3. Another way of thinking this problem: http://yucoding.blogspot.com/2013/04/leetcode-question-69-permutations.html
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> tem = new ArrayList<ArrayList<Integer>>();
if(num.length == 0) {
return res;
}
if(num.length == 1) {
ArrayList<Integer> cell = new ArrayList<Integer>();
cell.add(num[0]);
res.add(cell);
return res;
}
int [] arg = Arrays.copyOf(num, num.length-1);
int loc = num[num.length-1];
tem = permute(arg);
for(int i=0; i<=tem.size()-1; i++) { // the number of existing permutations
for(int j=0; j<=tem.get(i).size(); j++) { // possible positions for inserting
ArrayList<Integer> cell = new ArrayList<Integer>();
for(int m=0; m<j; m++) {
cell.add(tem.get(i).get(m));
}
cell.add(loc);
for(int n=j+1; n<=tem.get(i).size(); n++) {
cell.add(tem.get(i).get(n-1));
}
res.add(cell);
}
}
return res;
}
}