leetcode #64 in cpp

原创 2016年05月31日 01:00:16

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.


We use DP where dp[i][j] = minimum sum along the path from position(i+1,j+1) to the destination. 

Then dp[i][j] = min(dp[i+1][j], dp[i][j+1]) + grid[i][j]. That is, we select the direction which gives us a smaller sum, when we decide to take the next step.  


class Solution {
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size(); 
        vector<vector<int>> dp(m, vector<int>(n,0));
        dp[m-1][n-1] = grid[m-1][n-1];
        for(int i = m-2; i >= 0; i --){//right border
            dp[i][n-1] = grid[i][n-1] + dp[i+1][n-1];
        for(int i = n-2; i >= 0; i--){//bottom border
            dp[m-1][i] = grid[m-1][i]+dp[m-1][i+1];
        for(int i = m-2; i >= 0; i --){
            for(int j = n-2; j>=0; j --){
                dp[i][j] = min(dp[i+1][j], dp[i][j+1])+grid[i][j];//compare results from turning right and turning down
        return dp[0][0];

One optimization is to update the sum in place in grid instead of using the dp arrays. This saves us some memory. 



leetcode #32 in cpp

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...

leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

leetcode #98 in cpp

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined...

leetcode #37 in cpp

The question is to solve a Sudoku. Solution: We scan through the Sudoku. Whenever we meet a '.', w...

leetcode #77 in cpp

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exa...

leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

leetcode #18 in cpp

The question is similar to 3sum. And how to solve it is thus very similar to the solution of 3sum.  ...

leetcode #44 in cpp

Solution:  We use DP to solve this problem.  Initialize bool dp[pattern length + 1][ s length + 1]...