首页 > 代码库 > 动态规划-练习

动态规划-练习

动态规划范式

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>

 

动态规划-练习