Distinct subsequences
2016-07-25 16:30
393 查看
其实,动态规划有时候自己画个图一目了然:
没做优化前的代码:
public int numDistinct(String s, String t) {
int m = s.length();
int n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= Math.min(i, n); j++) {
dp[i][j] = dp[i - 1][j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m]
;
}
这种一般都可以做个空间优化,优化后如下:
public int numDistinct(String s, String t) {
int m = s.length();
int n = t.length();
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= m; i++) {
for (int j = Math.min(i, n); j > 0; j--) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[j] += dp[j - 1];
}
}
}
return dp
;
}
没做优化前的代码:
public int numDistinct(String s, String t) {
int m = s.length();
int n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= Math.min(i, n); j++) {
dp[i][j] = dp[i - 1][j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m]
;
}
这种一般都可以做个空间优化,优化后如下:
public int numDistinct(String s, String t) {
int m = s.length();
int n = t.length();
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= m; i++) {
for (int j = Math.min(i, n); j > 0; j--) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[j] += dp[j - 1];
}
}
}
return dp
;
}
相关文章推荐
- HBuilder底部选项卡的子页面切换效果
- IMS Modify Call (2) receive request 收到视频升级请求
- WEB-INF\classes 为空 The value for the useBean class attribute xxx is invalid
- UICollectionView Class Reference
- 论文阅读:Things, Trouble, Trust: On Building Trust in IoT Systems
- IMS Modify Call (1) send request 发出升级视频请求
- Develop>API Guides>Introduction>Device Compatibility 中文翻译
- UI系统技巧——制作血条与雷达图
- iOS开发封装篇-利用KVC修改UITextField的placeholderLabel颜色
- Vue 项目集合
- 67.The instance abnormally terminates because of a power outage. Which statement is true about redo
- easyui tree关闭所有节点
- QuerySet创建新对象的方法和获取对象的方法
- HBuilder底部选项卡,如何换图标呢
- C# return、continue、break
- 66.You notice that the performance of the database has degraded because of frequent checkpoints. Whi
- Java Programming Test Question 4
- POJ 3080 Blue Jeans KMP
- luigi学习-luigi的配置文件
- 【Android之实践】monkeyrunner采用对象id,进行UI自动化操作