Thursday, April 26, 2012

Generate Permutations

[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].

[Analysis]
Do it in a recursive way.

[Solution]

public static List<List<Integer>> generatePermutations ( List<Integer> nums ) {
List<List<Integer>> result = new ArrayList<List<Integer>> ();

if (nums.isEmpty()) return null;

if (nums.size()==1) {
result.add(nums);
return result;
}

Integer a = nums.get(0);
int numSize = nums.size();
nums.remove(0);
List<List<Integer>> subPerms = generatePermutations(nums);

for (int i=0; i<subPerms.size(); i++) {
for (int j=0; j<numSize-1; j++) {
List<Integer> newPerm = new ArrayList<Integer> (subPerms.get(i));
newPerm.add(j, a);
result.add(newPerm);
}
List<Integer> newPerm = new ArrayList<Integer> (subPerms.get(i));
newPerm.add(a);
result.add(newPerm);
}
return result;
}

No comments:

Post a Comment