Question:
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]
.
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> result = new ArrayList<Integer>();
dfs(num, results, result);
return results;
}
private void dfs(int[] num, ArrayList<ArrayList<Integer>> results,
ArrayList<Integer> result) {
if (num.length == 0) {
results.add(new ArrayList<Integer>(result));
return;
}
for (int i = 0; i < num.length; i++) {
int[] temp = new int[num.length - 1];
System.arraycopy(num, 0, temp, 0, i);
System.arraycopy(num, i + 1, temp, i, num.length - i - 1);
result.add(num[i]);
dfs(temp, results, result);
result.remove(result.size() - 1);
}
}
}