Given a collection of distinct 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 {
private void swap(Integer[] nums, int i, int j){
// Error: Note, i mustn't = j, or it clear the integer with bitwise method.
if(i == j)
return;
nums[i] = nums[i]^nums[j];
nums[j] = nums[i]^nums[j];
nums[i] = nums[i]^nums[j];
return;
}
public void permuteAux(Integer[] nums, int index, List> ret){
int len = nums.length;
if(index == len){
ArrayList t = new ArrayList(Arrays.asList(nums));
ret.add(t);
return;
}
for(int i = index; i < len; ++i){
swap(nums, index, i);
permuteAux(nums, index+1, ret);
swap(nums, index, i);
}
}
public List> permute(int[] nums) {
List> ret = new ArrayList>();
int len = nums.length;
if(0 == len)
return ret;
Integer[] iNums = new Integer[nums.length];
for(int i = 0; i < len; ++i){
iNums[i] = nums[i];
}
permuteAux(iNums, 0, ret);
return ret;
}
}
No comments:
Post a Comment