一类DP算法

DP应该是一种简单高效优美的算法,实在令人兴奋,近日在CSDN上解了几个问题,

 

发觉其实都接近同一类的DP问题,基本上的写法接近一种模式。

 

 

问题1: 式子上添加括号的最大值 (只有 +,-,*)

 

1+2*3这个例子
(1+2)*3=9这样算比1+(2*3)=7出来的结果要来得大
所以解答应为9

3*5+4这个例子
3*(5+4)=27这样算比(3*5)+4=19出来的结果要来得大
所以解答应为27

 

要点:把最大最小的都保存下来,中间可能出现负负得正

max[i][j]=当前数 (if i=j)
max[i][j]=max{max[i][k] op[k] max[k+1][j]} (if i <j)

 

min[i][j]=当前数 (if i=j)
min[i][j]=min{min[i][k] op[k] min[k+1][j]} (if i <j)

 

 

 

 

 

 

问题2:括号的枚举

 

 

 

比如 P = a,b,c,d .
乘积方案有
(a(b(cd)))
(a((bc)d))
((ab)(cd))
(((ab)c)d)
((a(bc))d)

 

 

DP(n,m) = DP(n,n+inc) + DP(n+inc+1,m); {inc (0 到 n+inc <m)}

DP[][]保存list产生所有的组合,再按上边的通式合并就是结果了

其实,每个分段就是一个递归的过程,当中产生的子问的重叠,用flag[][]

作标记,就可以达到记忆化了,减少运算

 

 

 

 

问题3:Parenthesize the string

 

Parenthesize the string。
Description
Let us define a multiplication operation on three symbols a,b,c according to the following table; thus ab = b, ba = c, and so on. Notice that the multiplication operation defined by the table is neither associative nor commutative.          
 

   a b c
a b b a
b c b a
c a c c

Find an efficient algorithm that examines a string of these symbols, say bbbbac, and decides whether or not it is possible to parenthesize the string in such a way that the value of the resulting expression is a. For example , on input bbbbac your algorithm should return yes because ((b(bb))(ba))c = a.
Input
Line 1: number K (1 <= K <= 100)
Line 2 … K+1: each of them is a test string.
Output
Line 1 … K : For each test case, output Yes or No.
Sample Input
2
bbbbac
abb
Sample Output
Yes
No

 

 

题目的意思是,把一个字符串按上边的矩阵的结合方式,能不能最终转换成字符a

 

每次的中间结果只有a,b,c,所以得到通式

 

DP[i][j][3] = DP[i][k][3]+DP[k+1][j][3]; (i<j)

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值