回溯法1

发布于 2023-12-25  736 次阅读


今天leetcode上刷到一题,名叫 全排列

差不多就是输出一个数组的所有排列情况
如 input: [1,2]
output: [1,2],[2,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);
        }
    }
}

其中的backtrack就是回溯法的标准方法,其中使用了 Collections.swap(output, first, i); 感觉以后可以用到。

原题链接: https://leetcode.cn/problems/permutations/

  • alipay_img
  • wechat_img
我是小明,喜欢数学和编程
最后更新于 2023-12-26