Given an array nums
of unique integers, return all the possible permutations. You may return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
public List> permute(int[] nums) {
List> res = new ArrayList<>();
if (nums.length == 1) {
List singleNum = new ArrayList<>();
singleNum.add(nums[0]);
res.add(singleNum);
return res;
}
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
int[] remainingNums = new int[nums.length - 1];
int idx = 0;
for (int j = 0; j < nums.length; j++) {
if (j != i) {
remainingNums[idx++] = nums[j];
}
}
List> perms = permute(remainingNums);
for (List perm : perms) {
perm.add(n);
res.add(new ArrayList<>(perm));
}
}
return res;
}