侧边栏壁纸
博主头像
阿里灰太狼博主等级

You have to believe in yourself . That's the secret of success.

  • 累计撰写 104 篇文章
  • 累计创建 50 个标签
  • 累计收到 12 条评论

目 录CONTENT

文章目录

leetcode-46. 全排列

阿里灰太狼
2021-12-14 / 0 评论 / 1 点赞 / 255 阅读 / 863 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2021-12-14,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

cj99.png

JAVA解法

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        // 定义一个保存结果的数组
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        // 定义一个保存传进来数组的数组
        List<Integer> output = new ArrayList<Integer>();
        // 遍历传进来的数组并存进 output
        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(path) path 为引用
            res.add(new ArrayList<Integer>(output));
        }
        // 每个 for 循环当前的 first 不变,i 在变,循环迭代
        for (int i = first; i < n; i++) {
            // 动态维护数组
            Collections.swap(output, first, i);
            // 继续递归填下一个数
            backtrack(n, output, res, first + 1);
            // 撤销操作
            Collections.swap(output, first, i);
        }
    }
}

题解分析

这道题用回归溯源的方法。首先定义一个保存结果的数组,定义一个保存传进来数组的数组,遍历传进来的数组并存进 output,获取传进来数组的长度,调用回溯算法得到结果,返回最终结果。

回溯算法实现如图:
cj100.png

leetcode原题: 46. 全排列

1

评论区