3

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:全排列

 1 year ago
source link: https://blog.51cto.com/u_13321676/5801634
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:全排列

精选 原创

灰太狼_cxh 2022-10-27 17:35:36 博主文章分类:leetcode ©著作权

文章标签 数组 全排列 递归 文章分类 Java 编程语言 阅读数180

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

输入:nums = [1,2,3]

输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

输入:nums = [0,1]

输出:[[0,1],[1,0]]

输入:nums = [1]

输出:[[1]]

代码实现:

class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();

List<Integer> output = new ArrayList<Integer>();
for (int num : nums) {
output.add(num);
}

int n = nums.length;
backtrack(n, output, res, 0);
return res;
}

public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
// 所有数都填完了
if (first == n) {
res.add(new ArrayList<Integer>(output));
}
for (int i = first; i < n; i++) {
// 动态维护数组
Collections.swap(output, first, i);
// 继续递归填下一个数
backtrack(n, output, res, first + 1);
// 撤销操作
Collections.swap(output, first, i);
}
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK