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],
[3,2,1]
]
Solution:
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
ans.add(new ArrayList<Integer>());
for(int i=0; i<nums.length; i++){
List<List<Integer>> newAns = new ArrayList<>();
for(List<Integer> list : ans){
/* for every postion */
for(int pos=0; pos<=i; pos++){
/* copy list */
List<Integer> newList = new ArrayList<>(list);
newList.add(pos, nums[i]);
newAns.add(newList);
}
}
ans = newAns;
}
return ans;
}
}