leetcode 46 Permutations

题目详情

Given a collection of distinct numbers, return all possible permutations.

题目要求我们对于输入的数字序列,给出它们的全排列。

例如,
[1,2,3] 有如下的全排列:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

想法

  • 这道题是用回溯法的思想解决的。
  • 回溯法在包含问题的所有解的解空间树中,按照深度优先的策略,从根节点出发深度优先搜索,搜索到某个点的时候,先判断该节点是否包含问题的解,如果包含就继续探索,否则就逐层向根节点回溯。

解法

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        
        backtrack(res,new ArrayList<Integer>(),nums);
        
        return res;
    }
    
    public void backtrack(List<List<Integer>> res ,List<Integer> tempList,int[] nums){
        if(tempList.size() == nums.length){
            res.add(new ArrayList<>(tempList));
        }else{
            for(int i=0;i<nums.length;i++){
                if(tempList.contains(nums[i])){
                    continue;
                }
                tempList.add(nums[i]);
                backtrack(res,tempList,nums);
                tempList.remove(tempList.size()-1);
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值