Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 17cca86

Browse files
add q1143
1 parent 126bbd2 commit 17cca86

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797
* [q70_爬楼梯](/src/动态规划/q70_爬楼梯)
9898
* [q118_杨辉三角](/src/动态规划/q118_杨辉三角)
9999
* [q300_最长上升子序列](/src/动态规划/q300_最长上升子序列)
100-
* [q746_使用最小花费爬楼梯](/src/动态规划/q746_使用最小花费爬楼梯)
100+
* [q1143_最长公共子序列](/src/动态规划/q1143_最长公共子序列)
101101
* [q1277_统计全为1的正方形子矩阵](/src/动态规划/q1277_统计全为1的正方形子矩阵)
102102

103103
### 回溯法
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package 动态规划.q1143_最长公共子序列;
2+
3+
/**
4+
* 动态规划 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n)
5+
*
6+
* 若题目为最长公共子串,则在c1,c2不相等时不做处理(赋值0),在遍历过程中记录最大值即可
7+
*/
8+
public class Solution {
9+
10+
public int longestCommonSubsequence(String text1, String text2) {
11+
int m = text1.length();
12+
int n = text2.length();
13+
int[][] dp = new int[m + 1][n + 1];
14+
15+
for (int i = 0; i < m; i++) {
16+
for (int j = 0; j < n; j++) {
17+
char c1 = text1.charAt(i);
18+
char c2 = text2.charAt(j);
19+
if (c1 == c2) {
20+
dp[i + 1][j + 1] = dp[i][j] + 1;
21+
} else {
22+
dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]);
23+
}
24+
}
25+
}
26+
return dp[m][n];
27+
}
28+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /