46. Permutations (Medium)
https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
Solutions
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ans;
}
doPermutation(nums, ans, 0);
return ans;
}
private void doPermutation(int[] nums, List<List<Integer>> ans, int depth) {
int len = nums.length;
// Reach the end of nums, add this solution to answer
if (depth == len - 1) {
List<Integer> solution = new ArrayList<>();
for (int n : nums) {
solution.add(n);
}
ans.add(solution);
return;
}
// For depth = 0, this first slot could be len situations from num[0] to num[len-1]
// Once the first slot determined, continue to go through rest elemennts
for (int j = depth; j < len; j++) {
swap(nums, depth, j);
doPermutation(nums, ans, depth + 1);
swap(nums, depth, j);
}
}
void swap(int[] nums, int x, int y) {
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
}