Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 27, 2012 16:34
Show Gist options
  • Save zac-xin/4389639 to your computer and use it in GitHub Desktop.
Save zac-xin/4389639 to your computer and use it in GitHub Desktop.
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) {
// Start typing your Java solution below
// DO NOT write main() function
return permuteHelper(num, 0);
}
public ArrayList<ArrayList<Integer>> permuteHelper(int num[], int index){
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(index == num.length - 1){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(num[index]);
result.add(list);
return result;
}else{
ArrayList<ArrayList<Integer>> partial = permuteHelper(num, index + 1);
for(ArrayList<Integer> list: partial){
for(int i = 0; i <= list.size(); i++){
ArrayList<Integer> tmp = new ArrayList<Integer>(list);
tmp.add(i, num[index]);
result.add(tmp);
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment