代码随想录算法训练营Day29|LC491 非递减子序列&LC46 全排列&LC47 全排列II

一句话总结:去重操作不是很理解。

原题链接:491 非递减子序列

照着模板吭哧写就完事了。去重操作稍微难想点。 

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> findSubsequences(int[] nums) {
        if (nums.length < 1) return ans;
        backTrack(nums, 0); 
        return ans;
    }

    private void backTrack(int[] nums, int start) {
        if (path.size() > 1) {
            ans.add(new ArrayList<>(path));
        }
        int[] used = new int[201];
        for (int i = start; i < nums.length; ++i) {
            if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || (used[nums[i] + 100] == 1)) continue;
            used[nums[i] + 100] = 1;
            path.add(nums[i]);
            backTrack(nums, i + 1);
            path.removeLast();
        }
    }
}

 原题链接:46 全排列

还是个很好的套模板的题目,去重操作也并不复杂。

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        backtrack(nums);
        return ans;
    }

    private void backtrack(int[] nums) {
        if (path.size() == nums.length) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (path.contains(nums[i])) continue;
            path.add(nums[i]);
            backtrack(nums);
            path.removeLast();
        }
    }
}

 原题链接:47 全排列II

主体还是套用模板,去重操作难一点,附原题解:题解 。

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        used = new boolean[nums.length];
        backTrack(nums);
        return ans;
    }

    private void backTrack(int[] nums) {
        if (path.size() == nums.length) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
           if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
           if (!used[i]) {
            used[i] = true;
            path.add(nums[i]);
            backTrack(nums);
            path.removeLast();
            used[i] = false;
           }
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值