Share my C++ DP solution with explanation


  • 2
    V
    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            int n = nums.size(), i = 0, j = 0, maxLen = 0, temp = 0;
            vector<int> length_dp(n, 1);
            
            for (i = 0; i < n; ++i)//compute length_dp[i],from i = 0 to n-1
            {
                for (j = 0; j < i; ++j)//length_dp[i] = max{length_dp[i],length_dp[j]+1|j<i && nums[j]<nums[i]}
                {
                    if (nums[j] < nums[i] && length_dp[i] < length_dp[j] + 1)
                        length_dp[i] = length_dp[j] + 1;
                }
                
                if (maxLen < length_dp[i])//update maxLen
                    maxLen = length_dp[i];
            }
            
            return maxLen;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.