当前位置:网站首页>Different subsequence problems I
Different subsequence problems I
2022-06-29 00:52:00 【GreyZeng】
Different subsequence problems I
author :Grey
Original address : Different subsequence problems I
Topic link
LeetCode 115. Different subsequences
Violence solution
Define recursive functions
int process(char[] str, char[] t, int i, int j)
Recursive functions represent :str from i All the way to the end , How many can the generated sequence match t from j The string generated later
therefore process(str,t,0,0) The result is the answer .
Next, consider the... Of recursive functions base case,
if (j == t.length) {
// Express str Have the t The whole thing is done , return 1, It shows that there is a situation
return 1;
}
// Here we are. , explain t It's not over yet
if (i == str.length) {
// str There are no strings anymore ,t It's not the end , therefore , Can't match
return 0;
}
Next up is the universal location , consider str[i] Whether to participate in matching determines the next operation , notes :str[i] If you want to participate in matching , Then we must satisfy str[i] == t[j].
// str[i] Position does not participate in matching
int ans = process(str, t, i + 1, j);
if (str[i] == t[j]) {
// str[i] Participate in , Must satisfy str[i] == t[j]
ans += process(str, t, i + 1, j + 1);
}
The complete code is as follows
public static int numDistinct(String s, String t) {
if (s.length() < t.length()) {
return 0;
}
return process(s.toCharArray(), t.toCharArray(), 0, 0);
}
// str[0.... ending ] Get it done t[0.... ending ]
public static int process(char[] str, char[] t, int i, int j) {
if (j == t.length) {
// It's all done
return 1;
}
if (i == str.length) {
// period , Uncertain
return 0;
}
// no need i The position should be fixed
int ans = process(str, t, i + 1, j);
if (str[i] == t[j]) {
ans += process(str, t, i + 1, j + 1);
}
return ans;
}
This violent solution is LeetCode Upper direct timeout .
Dynamic programming
Two dimensional array
According to the method of violence , You can get , A recursive function has only two mutable arguments , So define two dimensions dp,dp The meaning of is consistent with that of recursive function . therefore dp[0][0] That's the answer. .
int m = str.length;
int n = target.length;
int[][] dp = new int[m + 1][n + 1];
According to the method of violence
if (j == t.length) {
// It's all done
return 1;
}
if (i == str.length) {
// period , Uncertain
return 0;
}
You can get dp The last line of is 1, namely
for (int i = 0; i < m + 1; i++) {
dp[i][n] = 1;
}
Next consider the general dp[i][j], According to the method of violence
int ans = process(str, t, i + 1, j);
if (str[i] == t[j]) {
ans += process(str, t, i + 1, j + 1);
}
You can get ,dp[i][j] rely on dp[i+1][j] and dp[i+1][j+1]( Need to meet str[i] == t[j]) The value of the location .
therefore
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
dp[i][j] = dp[i + 1][j] + (str[i] == target[j] ? dp[i + 1][j + 1] : 0);
}
}
Complete code
public static int numDistinct(String s, String t) {
if (s.length() < t.length()) {
return 0;
}
char[] str = s.toCharArray();
char[] target = t.toCharArray();
int m = str.length;
int n = target.length;
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < m + 1; i++) {
dp[i][n] = 1;
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
dp[i][j] = dp[i + 1][j] + (str[i] == target[j] ? dp[i + 1][j + 1] : 0);
}
}
return dp[0][0];
}
Time complexity O(m*n), among m and n Namely s and t The length of .
Spatial complexity O(m*n), among m and n Namely s and t The length of .
One dimensional array
By analyzing the solution of the above dynamic programming , We can draw a conclusion , A two-dimensional dp The order of calculation is From the last line to the first line , And the current row only depends on the information of a limited number of positions in the previous row , therefore , We can simplify the above two-dimensional table into one-dimensional table , Definition
int m = str.length;
int[] dp = new int[n + 1];
Through the rolling update from the last row to the first row of the one-dimensional table , To get the value of the first row , The complete code is as follows
public static int numDistinct(String s, String t) {
if (s.length() < t.length()) {
return 0;
}
char[] str = s.toCharArray();
char[] target = t.toCharArray();
int m = str.length;
int n = target.length;
int[] dp = new int[n + 1];
dp[n] = 1;
for (int i = m - 1; i >= 0; i--) {
// Pay attention here , From left to right
for (int j = 0; j <= n - 1; j++) {
dp[j] += (str[i] == target[j] ? dp[j + 1] : 0);
}
}
return dp[0];
}
Time complexity O(m*n), among m and n Namely s and t The length of .
Spatial complexity O(n), among n yes t The length of .
more
边栏推荐
- 【SV 基础】queue 的一些用法
- 利用verilogA模块采样
- 滑环的基本结构及工作原理分析
- 最新Justnews主题源码6.0.1开心版+社交问答插件2.3.1+附教程
- 机器视觉系统的配件及工作过程
- Breadth first search to catch cattle
- Résumé de Manon, 25 ans, diplômé en trois ans
- 企业和IT领导者对创新的误解
- Mask wearing face data set and mask wearing face generation method
- Notes on the infrastructure of large websites
猜你喜欢

674. longest continuous increasing sequence
![[image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code](/img/b5/02979b50db885f0606dce455182ac4.jpg)
[image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code

Seven mistakes in IT Governance and how to avoid them
![[communication] wide band source DOA estimation method based on incoherent signal subspace (ISM)](/img/5d/bee9a6e50384a7e05e9a71e9fbed9a.jpg)
[communication] wide band source DOA estimation method based on incoherent signal subspace (ISM)

EasyCVR播放视频出现卡顿花屏时如何解决?

Remove HTML tags from Oracle

Realization of beauty system with MATLAB

戴口罩人脸数据集和戴口罩人脸生成方法

BMFONT制作位图字体并在CocosCreator中使用

光纤滑环价格过高的原因
随机推荐
Xuetong denies that the theft of QQ number is related to it: it has been reported; IPhone 14 is ready for mass production: four models are launched simultaneously; Simple and elegant software has long
Comics | goodbye, postman! One stop collaboration makes apipost more fragrant!
How to carry token authentication in websocket JS connection
Browser cache library design summary (localstorage/indexeddb)
var、let、const 三者的区别
Blazor University (34)表单 —— 获得表单状态
[image registration] improved SAR image registration based on sar-sift with matlab code
Uvm:factory mechanism
Operation level smart campus system source code smart campus applet source code + electronic class card + face recognition system
How does the JVM bottom layer implement synchronized
【UVM】我的 main_phase 都跑完了,为啥 case 无法退出?太不讲道理!
Is the fund reliable and safe
Report on the convenient bee Lantern Festival: the first peak sales of pasta products this year; prefabricated wine dumplings became the winners
大智慧上开户是安全的吗
【leetcode】17. Letter combination of telephone number
Analysis of basic structure and working principle of slip ring
[staff] accent mark, gradually stronger mark and gradually weaker mark
Précautions d'installation et d'utilisation des joints rotatifs
光纤滑环价格过高的原因
浏览器缓存库设计总结(localStorage/indexedDB)