Duplicating Most Voted c++ solution into java


  • 0
    X
    public int minPathSum(int[][] grid) {
    	int m = grid.length;
    	int n = grid[0].length;
    	int[][] sum = new int[m][n];
    	for (int[] row : sum)
    		Arrays.fill(row, grid[0][0]);
    	for (int i = 1; i < m; i++)
    		sum[i][0] = sum[i - 1][0] + grid[i][0];
    	for (int j = 1; j < n; j++)
    		sum[0][j] = sum[0][j - 1] + grid[0][j];
    	for (int i = 1; i < m; i++)
    		for (int j = 1; j < n; j++)
    			sum[i][j] = Math.min(sum[i][j - 1], sum[i - 1][j]) + grid[i][j];
    	return sum[m - 1][n - 1];
    }
    

    space O(n)

    time O(n)

    • 2 pass.
      • 1 pass to initialize,
      • 1 pass to solve sum.

    original post is herehttps://leetcode.com/discuss/38360/10-lines-28ms-o-n-space-dp-solution-in-c-with-explanations


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.