46. Permutations -Medium

Question

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

给出一个无重复数字的集合,返回所有的组合

Example

[1,2,3] have the following permutations:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Solution

  • 回溯解。它和subset问题的区别在于subset的123和213是一样的,即顺序是没用的,所以在回溯过程中我们会分别以数组的每一个元素作为头遍历,比如如下:

    for(int i = start;i < nums.length; i++){
        backtracking(nums, i + 1, res, temp);
    }

    而这里比如{1,2,3}的输入数组,假如我们当前头为2,如果仍然按照之前的算法,2前面的1将不会再遍历到,也就是我们会丢失213这个组合,如果在python中,我们可以通过切片来排除2并重新搜索,在java里我们必须每次都遍历整个数组,然后用temp.contain(nums[i])来判断该元素是否已添加:

    for(int i = 0; i < nums.length; i++){
        if(temp.contains(nums[i])) continue;
        backtracking(nums, res, temp);
    }

    完整代码如下:

    public class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            backtracking(nums, res, new ArrayList<>());
            return res;
        }
    
        public void backtracking(int[] nums, List<List<Integer>> res, List<Integer> temp){
            if(temp.size() == nums.length){
                res.add(new ArrayList<>(temp));
                return;
            }
            for(int i = 0; i < nums.length; i++){
                if(temp.contains(nums[i])) continue;
                temp.add(nums[i]);
                backtracking(nums, res, temp);
                temp.remove(temp.size() - 1);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值