Dynamic Programming (DP) is a commonly used algorithmic technique that can solve a wide range of practical problems. This article will introduce how to solve the Longest Increasing Subsequence (LIS) problem using the dynamic programming algorithm and provide concrete code examples.
The Longest Increasing Subsequence problem is to find a subsequence in a given integer sequence such that the elements in the subsequence are arranged in increasing order, and the subsequence is the longest possible. For example, in the sequence [10, 22, 9, 33, 21, 50, 41, 60, 80], the longest increasing subsequence is [10, 22, 33, 50, 60, 80] with a length of 6.
The dynamic programming algorithm typically uses a bottom-up approach, solving smaller subproblems first, and gradually solving larger problems. For the LIS problem, we define dp[i] to represent the length of the longest increasing subsequence ending at the i-th element. The state transition formula is as follows:
dp[i] = max(dp[j]) + 1, where 0 ≤ j < i
First, we define an array dp, initializing all elements to 1, which means each element is considered as a subsequence of length 1. Then, we iterate through the input integer sequence nums from left to right. For each element nums[i], we check all elements nums[j] where 0 ≤ j < i. If nums[j] < nums[i], we update dp[i]. After this, we simply iterate through the entire dp array to find the maximum value, which represents the length of the longest increasing subsequence.
function lengthOfLIS($nums) { $n = count($nums); $dp = array_fill(0, $n, 1); for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) { if ($nums[$j] < $nums[$i]) { $dp[$i] = max($dp[$i], $dp[$j] + 1); } } } $maxLen = 0; for ($i = 0; $i < $n; $i++) { $maxLen = max($maxLen, $dp[$i]); } return $maxLen; } $nums = array(10, 22, 9, 33, 21, 50, 41, 60, 80); $result = lengthOfLIS($nums); echo "The length of the Longest Increasing Subsequence is: " . $result;
The above code defines a function `lengthOfLIS` that takes an integer sequence nums as input and returns the length of the longest increasing subsequence. In the example provided, the output result is 6.
Using the dynamic programming algorithm, we can efficiently solve the Longest Increasing Subsequence problem. This algorithm also has wide applications in fields such as search engine optimization, data compression, and network transmission.
I hope this article helps you understand dynamic programming algorithms and allows you to apply them flexibly in real-world problems.