k神题解
转移方程dp[i][j] | 条件 |
---|
dp[i][j-2] dp[i-1][j] & s[i-1] = p[j-2] dp[i-1][j] & p[j-2] = ‘.’ | p[j-1]=’*’ | dp[i-1][j-1] & s[i-1] = p[j-1] dp[i-1][j-1] & p[j-1] =’.’ | p[j-1] ≠ ‘*’ |
public boolean isMatch(String s, String p) {
int m = s.length() + 1, n = p.length() + 1;
boolean[][] dp = new boolean[m][n];
dp[0][0] = true;
for(int j = 2; j < n; j += 2)
dp[0][j] = dp[0][j - 2] && p.charAt(j - 1) == '*';
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(p.charAt(j-1) == '*'){
if(s.charAt(i - 1) == p.charAt(j - 2) || p.charAt(j - 2) == '.'){
dp[i][j] = dp[i][j - 2] || dp[i - 1][j];
}else{
dp[i][j] = dp[i][j-2];
}
}else{
dp[i][j] = dp[i - 1][j - 1] && (p.charAt(j - 1) == '.' || s.charAt(i - 1) == p.charAt(j - 1));
}
}
}
return dp[m - 1][n - 1];
}
1,2,3,5
2的倍数、3的倍数、5的倍数
6的倍数,10的倍数,15的倍数,30的倍数
丑数递推 丑数 = 小丑数 × 某因子
x
n
+
1
=
m
i
n
(
x
a
×
2
,
x
b
?
×
,
x
c
×
5
)
x_n+_1 = min(x_a×2,x_b*×,x_c×5)
xn?+1?=min(xa?×2,xb??×,xc?×5) 动态规划
class Solution {
public int nthUglyNumber(int n) {
int a=0,b=0,c=0;
int[] dp= new int[n];
dp[0]=1;
for(int i=1;i<n;i++){
int n2 = dp[a]*2,n3=dp[b]*3,n5=dp[c]*5;
dp[i] = Math.min(Math.min(n2,n3),n5);
if(dp[i]==n2) a++;
if(dp[i]==n3) b++;
if(dp[i]==n5) c++;
}
return dp[n-1];
}
}
6n点数组合
k神题解
class Solution {
public double[] dicesProbability(int n) {
double[] dp = new double[6];
Arrays.fill(dp,1.0/6.0);
for(int i=2;i<=n;i++){
double[] tmp = new double[5*i+1];
for(int j=0;j<dp.length;j++){
for(int k=0;k<6;k++){
tmp[j+k] += dp[j] /6.0;
}
}
dp = tmp;
}
return dp;
}
}
|