动态规划-练习
Posted 国足不快乐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划-练习相关的知识,希望对你有一定的参考价值。
动态规划范式
var catch = [[],[]];
function someObscureFunction(a,b){
if(...) return ...;//先处理初始部分
var ret = catch[a][b];
if(ret) return ret
return catch[a][b] = 求解
}
练习1 通配符
* 长度大于等于0的字符串
? 任一字符串
例如:
he?p 匹配 help,heap,无法匹配helpp.
*p* 匹配papa
代码如下,这个算法的复杂度为O(n*n*n),n<=100 可以接受。
<script> function matchMemozied(W1,S1){ var cache = []; var W = W1.split(‘‘),S = S1.split(‘‘); function match(w,s){ var w1 = w,s1=s,ret; if(cache[w1]){ if(cache[w1][s1]){ return cache[w1][s1]; } }else{ cache[w1] = []; } while(s<S.length && w< W.length && (W[w] == ‘?‘ || W[w] == S[s])) { ++w; ++s; } if(w == W.length ) return cache[w1][s1] = s==S.length; if(W[w] == ‘*‘) { for(var i=0;i+s<=S.length;i++){ if(match(w1+1,s+i)){ return cache[w1][s1] = 1; } } } return cache[w1][s1] = 0; } if(match(0,0)){ console.log(S1); } } matchMemozied(‘he?p‘,‘heap‘); matchMemozied(‘he?p‘,‘heapp‘); matchMemozied(‘*p*‘,‘papa‘); </script>
代码二,O(n*n)
<script> function matchMemozied(W1,S1){ var cache = []; var W = W1.split(‘‘),S = S1.split(‘‘); function match(w,s){ var w1 = w,s1=s,ret; if(cache[w1]){ if(cache[w1][s1]){ return cache[w1][s1]; } }else{ cache[w1] = []; } if(s<S.length && w< W.length && (W[w] == ‘?‘ || W[w] == S[s])) { return cache[w1][s1] = match(w+1,s+1); } if(w == W.length ) return cache[w1][s1] = s==S.length; if(W[w] == ‘*‘) { if(match(w+1,s) || (s<S.length && match(w,s+1))) { return cache[w1][s1] = 1; } } return cache[w1][s1] = 0; } if(match(0,0)){ console.log(S1); console.log(cache); } } matchMemozied(‘he?p‘,‘heap‘); matchMemozied(‘he?p‘,‘heapp‘); matchMemozied(‘*p*‘,‘papa‘); </script>
以上是关于动态规划-练习的主要内容,如果未能解决你的问题,请参考以下文章