1、找到S[ i ] 决定的只是有效排列 P 中的相对大小,排列 P[ i + 1 ] 的值仅由 S[ i ] 和 P[ i ] 决定。
2、分别当S[i-1]为D,I时进行讨论
3、确认边界条件
可以适当写出下一步的结果从中发现规律
class Solution {
public int numPermsDISequence(String S) {
int mod = 1000000007;
int n = S.length();
char[] s = S.toCharArray();
int[][] dp = new int[n+1][n+1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++){
for (int j = 0; j <= i; j++){
if (s[i-1] == 'D'){
for (int k = j; k < i; k++){
dp[i][j] += dp[i-1][k];
dp[i][j] %= mod;
}
}else{
for (int k = 0; k < j; k++){
dp[i][j] += dp[i-1][k];
dp[i][j] %= mod;
}
}
}
}
int result = 0;
for (int i = 0; i <= n; i++){
result += dp[n][i];
result %= mod;
}
return result;
}
}
改进的动态规划
class Solution {
public int numPermsDISequence(String S) {
int mod = 1000000007;
int n = S.length();
char[] s = S.toCharArray();
int[][] dp = new int[n+1][n+1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++){
if (s[i-1] == 'D'){
for (int j = i - 1; j >= 0; j--){
dp[i][j] = dp[i][j+1] + dp[i-1][j];
dp[i][j] %= mod;
}
}else{
for (int j = 1; j <= i; j++){
dp[i][j] = dp[i][j-1] + dp[i-1][j-1];
dp[i][j] %= mod;
}
}
}
int result = 0;
for (int i = 0; i <= n; i++){
result += dp[n][i];
result %= mod;
}
return result;
}
}