Increasing Subsequences -LintCode

204 篇文章 0 订阅

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .

 注意事项
1.The length of the given array will not exceed 15.
2.The range of integer in the given array is [-100,100].
3.The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

样例

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

思路:
构建v[i],存放以nums[i]结尾的所有递增子数组。对于i,从j=i-1开始向前寻找nums[j]<=nums[i],如果nums[j]小于nums[i],可以将{nums[j],nums[i]}添加到v[i],并将v[j]中的子数组都添加nums[j],之后添加到v[i]中。若nums[j]等于nums[i],不再向前寻找避免重复。
例如{4,6,7,7}
v[0]为空;
v[1]={{4.6}};
对于v[2],6<7,添加{6,7},再添加v[1]中的元素{4,6,7},
4<7,添加{4,7},最终得到{{6,7},{4,6,7},{4,7}}
对于v[3],7<=7,添加{7,7},再添加v[2]中的元素{{6,7,7},{4,6,7,7},{4,7,7}},由于相等不再向前遍历,最终得到{{7,7},{6,7,7},{4,6,7,7},{4,7,7}}

#ifndef C1210_H
#define C1210_H
#include<iostream>
#include<vector>
#include<set>
using namespace std;
class Solution {
public:
    /**
    * @param nums: an integer array
    * @return: all the different possible increasing subsequences of the given array
    */
    vector<vector<int>> findSubsequences(vector<int> &nums) {
        // Write your code here
        vector<vector<int>> res;
        if (nums.empty() || nums.size() == 1)
            return res;
        int len = nums.size();
        vector<set<vector<int>>> v(len);//v[i]存放以nums[i]结尾的所有递增子数组
        for (int i = 1; i < len; ++i)
        {
            for (int j = i - 1; j >= 0; --j)
            {
                //对于i,从j=i-1开始向前寻找nums[j]<=nums[i]
                //如果nums[j]小于nums[i],可以将{nums[j],nums[i]}添加到v[i]
                //并将v[j]中的子数组都添加nums[j],之后添加到v[i]中
                //若nums[j]等于nums[i],不再向前寻找避免重复
                if (nums[j] <= nums[i])
                {
                    v[i].insert({ nums[j], nums[i] });
                    for (auto c : v[j])
                    {
                        vector<int> temp = c;
                        temp.push_back(nums[i]);
                        v[i].insert(temp);
                    }
                    if (nums[j] == nums[i])
                    {
                        break;
                    }
                }
            }
        }
        for (auto c : v)
        {
            for (auto t : c)
            {
                res.push_back(t);
            }
        }
        return res;
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值