二维dp,复杂度o(n^2),和斐波那契数列一样,当前源自两步,要么来自上,要么来自左。
流式编程处理输出输出。
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.nextLine()); int[][] ints = new int[n][n]; for(int i = 0; i < n; i++){ ints[i] = Arrays.stream(s.nextLine().split(",")).parallel().mapToInt(Integer::parseInt).toArray(); } // System.out.println(Arrays.deepToString(ints)); int[][] dp = new int[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i - 1 < 0 && j - 1 < 0){ dp[i][j] = ints[i][j]; }else if(i - 1 < 0){ dp[i][j] = dp[i][j - 1] + ints[i][j]; }else if(j - 1 < 0){ dp[i][j] = dp[i - 1][j] + ints[i][j]; }else{ dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + ints[i][j]; } } } System.out.println(dp[n - 1][n - 1]); } }