代码随想录算法训练营第二十九天 | 491. 递增子序列 & 46.全排列 & 47.全排列 II

1. 递增子序列

491. 递增子序列 - 力扣(LeetCode)

没有终止条件,因为要判断到最后一个元素,不能中途返回

路径上的后一个元素不能小于前一个元素

每层的元素也不能重复,用set去重(给定数组是无序的,不可排序)

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        backTracking(nums, 0);
        return res;
    }

    public void backTracking(int[] nums, int start){
        if(path.size() > 1){
            res.add(new ArrayList<>(path));
        }

        Set<Integer> set = new HashSet<>();
        for(int i = start; i < nums.length; i++){
            if(!path.isEmpty() && nums[i] < path.get(path.size()-1) || set.contains(nums[i])){
                continue;
            }
            set.add(nums[i]);
            path.add(nums[i]);
            backTracking(nums, i+1);
            path.remove(path.size()-1);
        }
    }
}
  • 时间复杂度: O(n * 2^n)
  • 空间复杂度: O(n)

2. 全排列

46. 全排列 - 力扣(LeetCode)

每层遍历都是从第一个元素开始,但是不能包括路径中已经存在的元素

class Solution {
    ArrayList<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        backTracking(nums);
        return res;
    }
    public void backTracking(int[] nums){
        if(path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(path.contains(nums[i]))
                continue;
            path.add(nums[i]);
            backTracking(nums);
            path.remove(path.size()-1);
        }
    }
}

3. 全排列 II

47. 全排列 II - 力扣(LeetCode)

自己的思路:

set判断每层的元素是否重复

map(index,value)判断该路径上当前元素是否被用过(值相等,下标相等)

class Solution {
    ArrayList<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    Map<Integer, Integer> map = new HashMap<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        backTracking(nums);
        return res;
    }
    
    public void backTracking(int[] nums){
        if(path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }
        Set<Integer> set = new HashSet<>();
        for(int i = 0; i < nums.length; i++){
            if(set.contains(nums[i]) || (map.get(i) != null && nums[i] == map.get(i)))
                continue;
            map.put(i, nums[i]);
            path.add(nums[i]);
            set.add(nums[i]);
            backTracking(nums);
            path.remove(path.size()-1);
            map.remove(i);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值