How to determine the longest increasing subsequence using dynamic programming?

前端 未结 19 2601
醉梦人生
醉梦人生 2020-11-22 10:55

I have a set of integers. I want to find the longest increasing subsequence of that set using dynamic programming.

19条回答
  •  不知归路
    2020-11-22 11:36

    Here are three steps of evaluating the problem from dynamic programming point of view:

    1. Recurrence definition: maxLength(i) == 1 + maxLength(j) where 0 < j < i and array[i] > array[j]
    2. Recurrence parameter boundary: there might be 0 to i - 1 sub-sequences passed as a paramter
    3. Evaluation order: as it is increasing sub-sequence, it has to be evaluated from 0 to n

    If we take as an example sequence {0, 8, 2, 3, 7, 9}, at index:

    • [0] we'll get subsequence {0} as a base case
    • [1] we have 1 new subsequence {0, 8}
    • [2] trying to evaluate two new sequences {0, 8, 2} and {0, 2} by adding element at index 2 to existing sub-sequences - only one is valid, so adding third possible sequence {0, 2} only to parameters list ...

    Here's the working C++11 code:

    #include 
    #include 
    
    int getLongestIncSub(const std::vector &sequence, size_t index, std::vector> &sub) {
        if(index == 0) {
            sub.push_back(std::vector{sequence[0]});
            return 1;
        }
    
        size_t longestSubSeq = getLongestIncSub(sequence, index - 1, sub);
        std::vector> tmpSubSeq;
        for(std::vector &subSeq : sub) {
            if(subSeq[subSeq.size() - 1] < sequence[index]) {
                std::vector newSeq(subSeq);
                newSeq.push_back(sequence[index]);
                longestSubSeq = std::max(longestSubSeq, newSeq.size());
                tmpSubSeq.push_back(newSeq);
            }
        }
        std::copy(tmpSubSeq.begin(), tmpSubSeq.end(),
                  std::back_insert_iterator>>(sub));
    
        return longestSubSeq;
    }
    
    int getLongestIncSub(const std::vector &sequence) {
        std::vector> sub;
        return getLongestIncSub(sequence, sequence.size() - 1, sub);
    }
    
    int main()
    {
        std::vector seq{0, 8, 2, 3, 7, 9};
        std::cout << getLongestIncSub(seq);
        return 0;
    }
    

提交回复
热议问题