一、简单动态规划问题
1、机器人走方格I
类似的参见《斐波那契数列》
有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。
给定两个正整数int x,int y,请返回机器人的走法数目。保证x+y小于等于12。
class Robot {
// public int times = 0;
// public int times1 = 0;
/*** 递归解法 **/
public int countWays1(int x, int y) {
if (x < 0 || y < 0)
return 0;
if (x == 0 || y == 0)
return 1;
// times1 ++;
return countWays1(x - 1, y) + countWays1(x, y - 1);
}
/** 优化的递归解法 **/
public int countWays(int x, int y) {
if (x < 0 || y < 0)
return 0;
int[][] counts = new int[x + 1][y + 1];
counts[0][0] = 1;
return countWays(x, y, counts);
}
private int countWays(int x, int y, int[][] counts) {
if (x < 0 || y < 0)
return 0;
if (counts[x][y] <= 0) {
counts[x][y] = countWays(x - 1, y, counts) + countWays(x, y - 1, counts);
// times ++;
}
return counts[x][y];
}
}
2、Minimum Path Sum (矩阵路径最小和问题)(leetcode 65)
1)问题描述:
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.
即给定一个m*n的数组矩阵,矩阵中所有值都是非负的;从左上角开始往右或者往下走,记录最终到达右下角的路径上所有元素之和的最小值问题;
2)问题分析:
简单的动态规划问题,记[i,j]位置元素的最小值为sum[i,j];