day 34 | ● 62.不同路径 ● 63. 不同路径 II

62.不同路径

day 34 | ● 62.不同路径 ● 63. 不同路径 II_第1张图片
递归公式为上 + 左

func uniquePaths(m int, n int) int {
    dp := make([][]int, m)
    for i := 0; i < m; i++{
        tmp := make([]int, n)
        dp[i] =tmp
        dp[i][0] = 1
    }
    for i := 0; i < n; i++{
        dp[0][i] = 1
    }

    for i := 1; i < m; i++{
        for j := 1; j < n; j++{
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        }
    }

    return dp[m - 1][n - 1]
}

63. 不同路径 II

day 34 | ● 62.不同路径 ● 63. 不同路径 II_第2张图片
石头的右边和下边都无法通过,所以赋初值的时候,当碰到石头,后面的均为0

func uniquePathsWithObstacles(obstacleGrid [][]int) int {
    dp := make([][]int, len(obstacleGrid))
    for i := 0; i < len(obstacleGrid); i++{
        tmp := make([]int, len(obstacleGrid[0]))
        dp[i] = tmp
    }
    for i := 0; i < len(obstacleGrid); i++{
        if obstacleGrid[i][0] == 1{
            break    
        }
        dp[i][0] = 1
    }

    for i := 0; i < len(obstacleGrid[0]); i++{
        if obstacleGrid[0][i] == 1{
            break    
        }
        dp[0][i] = 1
    }
    for i := 1; i < len(obstacleGrid);i++{
        for j := 1; j < len(obstacleGrid[0]); j++{
            if obstacleGrid[i][j] == 1{continue}
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        }
    }
    return dp[len(obstacleGrid) - 1][len(obstacleGrid[0]) - 1]
}

你可能感兴趣的:(数据结构与算法,算法,数据结构)