Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 491. Non-decreasing Subsequences

Rain Hu

491. Non-decreasing Subsequences


一、題目

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:

Example 2:

Constraints:


二、分析

三、解題

1. Backtracking

vector<vector<int>> findSubsequences(vector<int>& nums) {
    vector<vector<int>> res;
    vector<int> path;
    dfs(nums, 0, path, res);
    sort(res.begin(), res.end());               // 先做排序後
    for (int i = res.size()-1; i >= 1; i--) {   // 從後面往前迭代
        if (res[i] == res[i-1]) {
            res.erase(res.begin()+i);           // 刪除重覆的序列
        }
    }
    return res;
}
void dfs(vector<int>& nums, int i, vector<int>& path, vector<vector<int>>& res) {
    if (i == nums.size()) {         // 終止條件
        if (path.size() > 1) {      // 滿足子序列元素大於等於2個,則加入答案
            res.push_back(path);
        }
        return;
    }
    if (path.size() == 0 || nums[i] >= path.back()) {   // 注意需滿足題意為上升序列
        path.push_back(nums[i]);    // 加入子序列
        dfs(nums, i+1, path, res);
        path.pop_back();            // 回溯法需將元素 pop 掉
    }
    dfs(nums, i+1, path, res);      // 跳過不取
}

2. Backtracking(optimized)

vector<vector<int>> findSubsequences(vector<int>& nums) {
    vector<vector<int>> res;
    vector<int> path;
    dfs(nums, 0, path, res);
    return res;
}
void dfs(vector<int>& nums, int i, vector<int>& path, vector<vector<int>>& res) {
    if (i == nums.size()) {
        if (path.size() > 1) {
            res.push_back(path);
        }
        return;
    }
    if (path.size() == 0 || nums[i] >= path.back()) {
        path.push_back(nums[i]);
        dfs(nums, i+1, path, res);
        path.pop_back();
    }
    if (path.size() == 0 || nums[i] != path.back()) {   // 處理重覆子序列
        dfs(nums, i+1, path, res);
    }
    
}

回目錄 Catalog


Share this post on:

Previous
[Algo] 2-1. 暴力演算法 Brute Force
Next
[IT] C# Depth Ch.2 C# 2