[LeetCode]Permutations

本文介绍了一种基于深度优先搜索(DFS)的算法来找出一组不重复整数的所有可能排列。通过递归方式实现,确保了每一种排列都不会出现重复元素,并详细解释了如何避免递归过程中的副作用。

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

For 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]
]


本题难度Medium。

【复杂度】
时间 O(N!) 空间 O(N)

【思路】
就是用树的方法进行遍历。算法为DFS。

【注意】
1、本题说没有重复的数字(如果有就要进行检查)
2、在写递归程序时候要注意递归返回后有没有引起side effect。如果我不写代码30-31行,就会引起错误。代码26-31行相当于用了一个循环队列来进行各项遍历,遍历完了就恢复到初始状态,所以不会引起side effect。当然也可以这样写:

        for(int i=0;i<remains.size();i++){
            int n=remains.get(i); //be careful
            remains.remove(i);
            preList.add(n);
            helper(preList,remains,ans);
            preList.remove(preList.size()-1);
            remains.insert(i,n);
        }

不过报错:cannot find symbol: method insert(int,int)。可能方法名搞错了吧。
【代码】

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        //require
        List<List<Integer>> ans=new ArrayList<>();
        if(nums==null)
            return ans;
        int size=nums.length;
        if(size==0)
            return ans;
        List<Integer> remains=new ArrayList<Integer>(),list=new ArrayList<Integer>();
        for(int n:nums)
            remains.add(n);
        //invariant
        helper(list,remains,ans);
        //ensure
        return ans;
    }
    private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){
        //bound
        if(remains.size()==0){
            List<Integer> list=new ArrayList<Integer>(preList);
            ans.add(list);
            return;
        }
        for(int i=0;i<remains.size();i++){
            int n=remains.get(0);//be careful
            remains.remove(0);
            preList.add(n);
            helper(preList,remains,ans);
            preList.remove(preList.size()-1);
            remains.add(n);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值