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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix