动态规划一般可以将二维空间复杂度降低到一维的空间复杂度
O(n^2)
O(n)
import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); /** * 时间复杂度为O(n * m) * 空间复杂度为O(n) * * @param args */ public static void main(String[] args) { String s1 = sc.next(); String s2 = sc.next(); int ic = sc.nextInt(); int dc = sc.nextInt(); int rc = sc.nextInt(); char[] c1 = s2.toCharArray(); int n1 = s2.length(); char[] c2 = s1.toCharArray(); int n2 = s1.length(); // 一行的改变 int[] dp = new int[n1+1]; dp[0] = 0; for(int i=1;i<=n1;i++){ dp[i] = i * ic; } // s2[0...i] => s1[0...j] 记为 dp[i][j] for(int i=1;i<=n2;i++){ int[] dp2 = new int[n1+1]; dp2[0] = dc * i; // 一行一行来 for(int j=1;j<=n1;j++){ dp2[j] = Integer.MAX_VALUE; if(c2[i-1] == c1[j-1]){ dp2[j] = Math.min(dp2[j], dp[j-1]); } dp2[j] = Math.min(dp2[j], dp[j] + dc); // 减少 dp2[j] = Math.min(dp2[j], dp[j-1] + rc); // 修改 dp2[j] = Math.min(dp2[j], dp2[j-1] + ic); // 修改 } for(int k=0;k<=n1;k++){ dp[k] = dp2[k]; } } System.out.println(dp[n1]); } } /* '' a d c '' 0 5 10 15 a 3 0 5 10 b 6 c 9 abc adc 5 3 2 2 */
import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); /** * 时间复杂度为O(n * m) * 空间复杂度为O(n) * * @param args */ public static void main(String[] args) { String s1 = sc.next(); String s2 = sc.next(); int ic = sc.nextInt(); int dc = sc.nextInt(); int rc = sc.nextInt(); char[] c1 = s2.toCharArray(); int n1 = s2.length(); char[] c2 = s1.toCharArray(); int n2 = s1.length(); int[][] dp = new int[n2+1][n1+1]; dp[0][0] = 0; for(int i=1;i<=n1;i++){ dp[0][i] = i * ic; } for(int i=1;i<=n2;i++){ dp[i][0] = i * dc; } // s2[0...i] => s1[0...j] 记为 dp[i][j] for(int i=1;i<=n2;i++){ // 一行一行来 for(int j=1;j<=n1;j++){ dp[i][j] = Integer.MAX_VALUE; if(c2[i-1] == c1[j-1]){ dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1]); } dp[i][j] = Math.min(dp[i][j], dp[i][j-1] + ic); // 增加 dp[i][j] = Math.min(dp[i][j], dp[i-1][j] + dc); // 减少 dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + rc); // 修改 } } System.out.println(dp[n2][n1]); } } /* '' a b c '' 0 a d c abc adc 5 3 2 2 */