首页 > 其他 > 详细

LeetCode46 全排列

时间:2021-06-27 13:30:35      阅读:19      评论:0      收藏:0      [点我收藏+]

题目

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

示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:
输入:nums = [1]
输出:[[1]]

提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同

方法

回溯法(DFS)

  • 时间复杂度:O(n*n!),参考:leetcode官方解答
  • 空间复杂度:O(n),辅助数组长度为n,递归栈也为n
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        for(int num:nums){
            tmp.add(num);
        }
        dfs(nums,0);
        return result;
    }
    private void dfs(int[]nums,int depth){
        if(depth==nums.length){
            result.add(new ArrayList(tmp));
            return;
        }
        for(int i=depth;i<nums.length;i++){
            Collections.swap(tmp,depth,i);
            dfs(nums,depth+1);
            Collections.swap(tmp,depth,i);
        }
    }
}

LeetCode46 全排列

原文:https://www.cnblogs.com/ermiao-zy/p/14940085.html

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