zoukankan      html  css  js  c++  java
  • js动态规划---最长子序列(lcs)

    		function LCS(wordX, wordY) {
    			var m = wordX.length;
    			var n = wordY.length;
    			this.lcs = function(){
    				var l = [];
    				var path = [];
    				var i, j, a, b;
    				for(i = 0; i <= m; ++i) {
    					l[i] = [];
    					path[i] = [];
    					for(j = 0; j <= n; j++) {
    						l[i][j] = 0;
    						path[i][j] = 0;
    					}
    				}
    	
    				for(i = 1; i <= m; i++) {
    					for(j = 1; j <= n; j++) {
    						if(wordX[i - 1] == wordY[j - 1]) {
    							l[i][j] = l[i - 1][j - 1] + 1;
    							path[i][j]  = 1; //取左上角
    						} else {
    							a = l[i - 1][j]; //取上边
    							b = l[i][j - 1];  //取左边
    							if(b >= a){
    								l[i][j] = b;
    								path[i][j] = 2; 
    							}else{
    								l[i][j] = a;
    								path[i][j] = 3;
    							}
    						}
    					}
    				}
    				return {
    					l:l,
    					p:path,
    					len:l[m][n]
    				};
    			}
    			
    			this.getPath = function(){
    				var obj = this.lcs();
    				var p = obj.p;
    				var l = obj.l;
    				var list = [];
    				print(m,n,list);
    				
    				function print(i,j,list){
    					var typ = p[i][j];
    					
    					if(i==0 || j==0){
    						return ;
    					}
    					
    					console.log(i,j,typ,wordX[i-1],wordY[j-1])
    					if(typ == 1){
    						print(i-1,j-1,list);
    						list.push(wordX[i-1]); //为1时,表示 wordx[i-1]=wordy[j-1],任意取一个
    					}
    					if(typ == 2){
    						print(i,j-1,list);
    					}
    					
    					if(typ == 3){
    						print(i-1,j,list);
    					}
    				}
    				
    				return list;
    				
    			}
    
    		}
    		
    		var lcs = new LCS('ABCADAB', 'BACDBA');
    		console.log(lcs.lcs());
    		console.log(lcs.getPath());
    		//B A D B
    		
    		//l[i][j] 表示 stri , strj 最大公共子序列
    		//如果 str1[i] == str2[j], 则 l[i][j] = l[i-1][j-1] + 1;
    		//如果 str1[i] != str2[j],则 l[i][j] = max(l[i-1][j],l[i][j-1]) ;
    

      

  • 相关阅读:
    lampp、xampp安装文档
    tomcat下配置https方式
    1.6:怎么学习Linux
    1.5:linux的应用领域
    1.3:linux的优点和缺点
    1.4:Linux发行版本详解
    1.2:liunx和unix的区别
    1.1:Linux系统简介
    mysql中获取表名&字段名的查询语句
    kettle组件-输出
  • 原文地址:https://www.cnblogs.com/muamaker/p/9322935.html
Copyright © 2011-2022 走看看