目录
- class Solution {
- public:
- int longestCommonSubsequence(string text1, string text2) {
- vector
int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0)); - for (int i = 1; i <= text1.size(); i++) {
- for (int j = 1; j <= text2.size(); j++) {
- if (text1[i - 1] == text2[j - 1]) {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- } else {
- dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
- }
- }
- }
- return dp[text1.size()][text2.size()];
- }
- };
- class Solution {
- public:
- int maxUncrossedLines(vector<int>& A, vector<int>& B) {
- vector
int>> dp(A.size() + 1, vector<int>(B.size() + 1, 0)); - for (int i = 1; i <= A.size(); i++) {
- for (int j = 1; j <= B.size(); j++) {
- if (A[i - 1] == B[j - 1]) {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- } else {
- dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
- }
- }
- }
- return dp[A.size()][B.size()];
- }
- };
- class Solution {
- public:
- int maxSubArray(vector<int>& nums) {
- if (nums.size() == 0) return 0;
- vector<int> dp(nums.size());
- dp[0] = nums[0];
- int result = dp[0];
- for (int i = 1; i < nums.size(); i++) {
- dp[i] = max(dp[i - 1] + nums[i], nums[i]); // 状态转移公式
- if (dp[i] > result) result = dp[i]; // result 保存dp[i]的最大值
- }
- return result;
- }
- };