动态规划算法,最小代价
2015-06-22 16:19
190 查看
<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">将一个字符串通过插入字符串或者删除字符串的方式转换为另一个给定的字符串。删除连续n个字符的操作的代价为2,插入n个字符的代价为n+2。求转换的最小代价。</span>
<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);"> </span>
package com.test; import com.copy.test.Demo1CopyTest; public class Demo { public static void main(String[] args) { GetMinExpenses("AABB", "BB"); } public static int DEL = -1; public static int ORIGAL = 0; public static int ADD = 1; public static int getAddCount(int f, int type) { int minCost; if (type == ADD) { minCost = f + 1; } else { minCost = f + 3; } return minCost; } public static int getDelCount(int f, int type) { int minCost = 0; if (type == DEL) { minCost = f + 0; } else { minCost = f + 2; } return minCost; } public static int getMin(int a, int b) { return a < b ? a : b; } public static int GetMinExpenses(String aString, String bString) { int[][] f = new int[aString.length() + 1][bString.length() + 1];//f[i][j] 从a[i] -> b[j]的最小代价 f[0][0] = 0; int operator[][] = new int[aString.length() + 1][bString.length() + 1];//用于记录操作 for (int i = 1; i < aString.length() + 1; i++) { f[i][0] = 2; operator[i][0] = DEL; } for (int i = 1; i < bString.length() + 1; i++) { f[0][i] = 2 + i; operator[0][i] = ADD; } int type = ORIGAL; for (int i = 1; i < aString.length() + 1; i++) { // System.out.println(); for (int j = 1; j < bString.length() + 1; j++) { // System.out.print(minCost + "_" + operator[i][j] + " "); int tempType; int cost = 0; if (aString.charAt(i - 1) != bString.charAt(j - 1)) { cost = 5; } int minCost; int delCount = getDelCount(f[i - 1][j], operator[i - 1][j]); int addCount = getAddCount(f[i][j - 1], operator[i][j - 1]); if (delCount >= addCount) { operator[i][j] = ADD; minCost = addCount; } else { operator[i][j] = DEL; minCost = delCount; } if (minCost > f[i - 1][j - 1] + cost) { operator[i][j] = ORIGAL; minCost = f[i - 1][j - 1] + cost; } f[i][j] = minCost; } // System.out.println(""); } return f[aString.length()][bString.length()]; } }
相关文章推荐
- 常用正则表达式
- eth_mac_address没找到
- javascript基础知识--函数定义
- Combox默认项设置的问题及解决方案
- Cocos2d-x三国ACT手游《热血斩将》完整源码下载
- maven下载源代码,中文注释乱码的处理方法
- html5学习笔记(1)
- LA 4080 warfare And Logistics (Dijkstra)
- 地图两点之间获取距离公式
- NetRouter开发板---基于7620a开源openwrt开发板系列教程(一)
- angular依赖注入的理解(转)
- C#中的里氏替换原则
- Stata编程运用-运用递归函数列示文件夹内所有文件
- 验证码图片生成以及页面取得
- 两种方式实现类似qq搜索的切换
- C++静态局部对象
- linux sysfs下创建文件
- 上传excel文件
- PL/SQL Developer 导出csv文件,用excel打开中文显示乱码
- 散列表的查找代码实现