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;
}
posted @   MarkLeeBYR  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示