最长递增子序列的长度,O(n)复杂度

时间:2018-08-26 16:59:54

标签: algorithm dynamic-programming

此函数是否返回数组A []中存在的递增子序列的最大长度?

// Interface for event listening
template <typename Event, typename Sender>
class EventListener
{
public:
    virtual ~EventListener() = default;
    virtual void onEvent(const Sender* sender, const Event& data) = 0;
};

// Abstract class for event publishing
template <typename Event, typename Sender>
class EventPublisher
{
public:
    typedef EventListener<Event, Sender> Listener;
    virtual ~EventPublisher() = default;

    // Queues an event listener
    void attach(Listener* listener) {
        listeners.push_back(listener);
    }

protected:
    // Publishes an event among all registered listeners
    void publish(const Event& e) {
        for (Listener* listener : listeners) {
            listener->onEvent(static_cast<Sender *>(this), e);
        }
    }

private:
    std::vector<Listener*> listeners;
};

// Concrete publisher & listener
class StateEvent {};
class StateEventPublisher : public EventPublisher<StateEvent, StateEventPublisher> {};
class StateEventListener : public EventListener<StateEvent, StateEventPublisher> {};

class State : public StateEventPublisher {
public:
    void foo() {
        publish(StateEvent());
    }
};

class StateMachine final : public StateEventListener {
private:
    void onEvent(const StateEventPublisher* sender, const StateEvent& e) override {}
};

int main()
{
    State state;
    StateMachine machine; // Is a StateEventListener, which is a EventListener<StateEvent, StateEventPublisher>, whereas StateEventPublisher is a EventPublisher<StateEvent>

    state.attach(&machine); // Incompatible with EventListener<StateEvent, EventPublisher<StateEvent>>*
    state.foo();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

以上解决方法不正确。上面的代码用于最长的递增序列,而不是子序列。对于最长的递增子序列检查 https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/