首页 > 其他 > 详细

[LeetCode] 46. 全排列

时间:2021-02-20 11:59:46      阅读:34      评论:0      收藏:0      [点我收藏+]




给定一个 没有重复 数字的序列,返回其所有可能的全排列。

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

分析

  • 回溯算法

解法

  • 定义递归函数,dfs(depth, tmp, used)

    • depth为当前递归层数
    • tmp为当前排列
    • used为标记数组判断数字是否使用过
  • 递归结束条件为填完n个位置

  • 时间复杂度O(\(n \times n!\)),n为序列长度

  • 空间复杂度O(n)

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        // 结果列表
        List<List<Integer>> ans = new ArrayList<>();
        int len = nums.length;
        if (len == 0) return ans;
        // 初始化当前排列
        List<Integer> tmp = new ArrayList<>();
        // 标记数组
        boolean[] used = new boolean[len];
        dfs(nums, ans, len, 0, tmp, used);
        return ans;
    }

    /**
     * @param nums  目标数组
     * @param ans   最终结果列表
     * @param len   数组长度
     * @param depth 当前递归深度
     * @param tmp   当前排列
     * @param used  标记数组
     */
    private void dfs(int[] nums, List<List<Integer>> ans, int len, int depth, List<Integer> tmp, boolean[] used) {
        // 递归结束条件未递归深度等于数组长度
        if (depth == len) {
            ans.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = 0; i < len; i++) {
            // 当前数字已被使用
            if (used[i]) continue;
            // 当前数字未被使用
            tmp.add(nums[i]);
            used[i] = true;
            // 进行下一层递归
            dfs(nums, ans, len, depth + 1, tmp, used);
            // 回溯
            tmp.remove(tmp.size() - 1);
            used[i] = false;
        }
    }
}

//class Test{
//    public static void main(String[] args) {
//        Solution test = new Solution();
//        int[] nums = {1,2,3};
//        System.out.println(test.permute(nums));
//    }
//}

[LeetCode] 46. 全排列

原文:https://www.cnblogs.com/lijiong/p/14419544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!