一、简单动态规划问题
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)问题

本文汇总了程序员面试中常见的递归问题,包括在XxY网格中机器人从左上角到达右下角的不同走法计数,以及如何找到集合的所有非空子集。通过递归和迭代法解决这些问题,并提供了相关代码示例。同时讨论了字符串排列组合及数组中的魔术索引问题,提出高效解决方案。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



