leetcode每日一题之9.最长递增子序列

最长递增子序列

参考

动态规划1

定义dp[i]:结尾为i的最长序列长度.

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function lengthOfLIS($nums) {
        $length = count($nums);
        if($length < 2) return $length;

        $dp = array_fill(0, $length, 1);
        for($i = 0; $i < $length; ++$i){
            for($j = 0; $j < $i; ++$j){
                if($nums[$i] > $nums[$j]){
                    $dp[$i] = max($dp[$i], $dp[$j] + 1);
                }
            }
        }

        $res = 1;
        for($i= 0; $i < $length; ++$i){
            $res = max($res, $dp[$i]);
        }
        return $res;
    }
}

动态规划2

定义tail[i] 为同等长度下,结尾元素最小的值。

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function lengthOfLIS($nums) {
        $length = count($nums);
        if($length < 2) return $length;

        $tail = [$nums[0]];
        $end = 0;
        for($i = 1; $i < $length; ++$i){
            if($nums[$i] > $tail[$end]){
                $tail[++$end] = $nums[$i];
            } else {
                // 使用二分查找找到合适的位置 然后替换
                $left = 0;
                $right = $end;
                while($left < $right){
                    $middle = floor(($right + $left) / 2);
                    if($tail[$middle] < $nums[$i]){
                        $left = $middle + 1;
                    } else {
                        $right = $middle;
                    }
                }
                $tail[$left] = $nums[$i];
            }
        }

        $end++;
        return $end;
    }
}

原文地址:https://www.cnblogs.com/qiye5757/p/14500371.html