46. Permutations
Given an array nums of distinct integers, return all the possible permutations. You can 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]]
Example 2:
Input: nums = [0,1] Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1] Output: [[1]]
和 https://www.cnblogs.com/MarkLeeBYR/p/16887119.html 数组的子集解法相同
本题和78题不一样,递归传入的是index+1,78题递归传入的是j+1。递归路径:
helper(0) -> j=0,helper(1) -> j=1,helper(2) -> j=2,helper(3) -> j=3
-> j=2,helper(2) -> j=2,helper(3) -> j=3
-> j=3
-> j=1,helper(1) -> j=1,helper(2) -> j=2,helper(3) -> j=3
-> j=2,helper(2) -> j=2,helper(3) -> j=3
-> j=3
-> j=2,helper(1) -> j=1,helper(2) -> j=2,helper(3) -> j=3
-> j=2,helper(2) -> j=2,helper(3) -> j=3
-> j=3
-> j=3
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
helper(res, nums, 0);
return res;
}
private void helper(List<List<Integer>> res, int[] nums, int index) {
if (index == nums.length) {
List<Integer> temp = new ArrayList<>();
for (int num : nums) {
temp.add(num);
}
res.add(temp);
return;
}
for (int j = index; j < nums.length; j++) {
swap(nums, j, index);
helper(res, nums, index + 1);
swap(nums, j, index);
}
}
private void swap(int[] nums, int m, int n) {
int temp = nums[m];
nums[m] = nums[n];
nums[n] = temp;
}
浙公网安备 33010602011771号