Thought:
Recursion.
Code:
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cache = new ArrayList<Integer>();
if (num.length == 1) {
cache.add(num[0]);
result.add(cache);
return result;
}
int first = num[0];
int[] previous = Arrays.copyOfRange(num, 1, num.length);
ArrayList<ArrayList<Integer>> temp = permute(previous);
for (ArrayList<Integer> list : temp) {
for (int i = 0; i <= list.size(); i++) {
list.add(i, first);
result.add(new ArrayList<Integer>(list));
list.remove(i);
}
}
return result;
}
}
No comments:
Post a Comment