代码随想录day29|491.递增子序列 |46.全排列 |47.全排列 II

文章介绍了两种基于回溯法的算法实现,分别是寻找给定整数数组中的递增子序列和全排列,以及优化版本的全排列II,通过使用哈希集和used数组判断元素是否已使用。

491.递增子序列

class Solution {
     List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        backTracking(nums, 0);
        return result;
    }
    private void backTracking(int[] nums, int startIndex){
        if(path.size() >= 2)
                result.add(new ArrayList<>(path));            
        HashSet<Integer> hs = new HashSet<>();
        for(int i = startIndex; i < nums.length; i++){
            if(!path.isEmpty() && path.get(path.size() -1 ) > nums[i] || hs.contains(nums[i]))
                continue;
            hs.add(nums[i]);
            path.add(nums[i]);
            backTracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}

46.全排列 

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;
    public List<List<Integer>> permute(int[] nums) {
        if (nums.length == 0){
            return res;
        }
        used = new boolean[nums.length];
        test(nums);
        return res;
    }

    public void test(int []nums){
        if(path.size()==nums.length){
            res.add(new ArrayList<Integer>(path));
            return;
        }

        for(int i=0;i<nums.length;i++){
            if(used[i]){
                continue;
            }
            used[i] =true;
            path.add(nums[i]);
            test(nums);
            path.removeLast();
            used[i] = false;
        } 
    }
}

47.全排列 II 

通过uesd数组来进行判断前一个用过还是没用过,然后再通过used[i-1]来判断同一树层的数据是否使用过

class Solution {
    List<Integer> path = new ArrayList<Integer>();
    LinkedList<List<Integer>> res = new LinkedList<>(); 
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        test(nums, used);
        return res;
    }

    public void test(int nums[],boolean[] used){
        if(path.size()==nums.length){
            res.add(new ArrayList(path));
            return;
        }
        for(int i=0;i<nums.length;i++){
            if(i>0&&nums[i]==nums[i-1]&&used[i-1]==false){
                continue;
            }
            if(used[i]==false){
                used[i]=true;
                path.add(nums[i]);
                test(nums,used);
                path.remove(path.size()-1);
                used[i]=false;
            }
        }
        
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值