|
| 1 | +/** |
| 2 | + * Solution: Dynamic programming |
| 3 | + * match[i][j], the number of matched substrings when s with the length i and t with the length j. |
| 4 | + * if s[i-1] !== s[j-1], then the matched number equals to the matched number of s with length i - 1. |
| 5 | + * that is, match[i][j] = match[i-1][j]. |
| 6 | + * if s[i-1] == s[j-1], the matched number is the mathched number when s with length i - 1 and t with length j, |
| 7 | + * plus the matched number when s with i - 1 length and t with j - 1 length. |
| 8 | + * |
| 9 | + *@param {string} s |
| 10 | + *@param {string} t |
| 11 | + *@return {number} |
| 12 | + */ |
| 13 | +varnumDistinct=function(s,t){ |
| 14 | +if(!s)return0; |
| 15 | + |
| 16 | +varmatch=[]; |
| 17 | +for(vari=0;i<=s.length;i++){ |
| 18 | +match[i]=[1]; |
| 19 | +} |
| 20 | + |
| 21 | +for(varj=1;j<=t.length;j++){ |
| 22 | +match[0][j]=0; |
| 23 | +} |
| 24 | + |
| 25 | +for(i=1;i<=s.length;i++){ |
| 26 | +for(j=1;j<=t.length;j++){ |
| 27 | +if(s[i-1]===t[j-1])match[i][j]=match[i-1][j-1]+match[i-1][j]; |
| 28 | +elsematch[i][j]=match[i-1][j]; |
| 29 | +} |
| 30 | +} |
| 31 | + |
| 32 | +returnmatch[s.length][t.length]; |
| 33 | + |
| 34 | +}; |
| 35 | + |
| 36 | +// just use one dimension array to store matched numbers |
| 37 | +varnumDistinct=function(s,t){ |
| 38 | +if(!s)return0; |
| 39 | +if(t.length>s.length)return0; |
| 40 | + |
| 41 | +vartLength=t.length; |
| 42 | +varsLength=s.length; |
| 43 | + |
| 44 | +vardp=[1]; |
| 45 | +for(vari=1;i<=tLength;i++){ |
| 46 | +dp.push(0); |
| 47 | +} |
| 48 | + |
| 49 | +for(i=1;i<=sLength;i++){ |
| 50 | +for(j=tLength;j>=1;j--){ |
| 51 | +if(s[i-1]===t[j-1])dp[j]+=dp[j-1]; |
| 52 | +} |
| 53 | +} |
| 54 | + |
| 55 | +returndp[tLength]; |
| 56 | + |
| 57 | +}; |