LeetCode每日一题(491. Non-decreasing Subsequences)

给定整数数组nums,返回所有可能的不同非递减子序列,至少包含两个元素。例如,对于输入[4,6,7,7],输出包括[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]。" 106463221,7458683,Ubuntu虚拟机在VMware中扩大磁盘容量,"['Linux', 'VMware', 'Ubuntu', '磁盘管理', '操作系统']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.

Example 1:

Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:

Input: nums = [4,4,3,2,1]
Output: [[4,4]]

Constraints:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

没有技巧, 硬做就好



use std::collections::HashSet;

impl Solution {
    pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
        let mut set = HashSet::new();
        let mut ans: Vec<Vec<i32>> = Vec::new();
        for i in 0..nums.len() {
            for j in 0..ans.len() {
                // 如果当前数字大于任意递增数组的最后一个数字, 则复制该递增数组并将当前数字push进copy,并将copy放到ans中
                if nums[i] >= ans[j][ans[j].len() - 1] {
                    let mut l = ans[j].clone();
                    l.push(nums[i]);
                    if set.contains(&l) {
                        continue;
                    }
                    set.insert(l.clone());
                    ans.push(l);
                }
            }
            ans.push(vec![nums[i]])
        }
        // 过滤出长度>1的递增数组
        ans.into_iter().filter(|l| l.len() > 1).collect()
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值