不同子序列
不同的子序列
public int numDistinct (String S, String T) {
// write code here
int row = S.length();
int col = T.length();
int[][] f = new int[row+1][col+1];
f[0][0] = 1;
for(int i=1;i<row+1;i++){
f[i][0] = 1;
for(int j=1;j<col+1;j++){
if(S.charAt(i-1)==T.charAt(j-1)){
f[i][j] = f[i-1][j-1]+f[i-1][j];
}else{
f[i][j] = f[i-1][j];
}
}
}
return f[row][col];
}
此时我们发现,我们只是用的上一行的数据,所以我们可以做出优化,只保存上一行的数据
由于要使用上一行的数据,所以我们从后往前遍历
public int numDistinct (String S, String T) {
// write code here
int row = S.length();
int col = T.length();
int[] f = new int[col+1];
f[0] = 1;
for(int i=1;i<row+1;i++){
for(int j=col;j>=1;j--){
if(S.charAt(i-1)==T.charAt(j-1)){
f[j] = f[j-1]+f[j];
}
}
}
return f[col];
}
动规一点也不难!!!?