<数据结构与算法>——动态规划入门(1)

动态规划是一种解决问题的指导思想。

1.例题

  1. Triangle
    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
    For example, given the following triangle
    [
    [2],
    [3,4],
    [6,5,7],
    [4,1,8,3]]
    The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
    NOTE:
    Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

2.分析

1. 根据题目,可采用深度优先搜索方法。

深度优先搜索中,类似于二叉树的递归算法,有两种策略: 遍历和分治。

  1. 采用遍历 traverse, 把要变化的值(这里是sum)作为dfs递归函数的参数,在传递过程中使用。
    这里dfs的定义是,走到当前下(x,y)这个点的和为sum,这个sum随着点的下移在变化,因此把sum作为dfs的一个参数。
// traverse
void dfs(int x, int y, int sum) {
   if (x == n) {
       if (sum < best) {
           best = sum;
       }
       return;
   }
   // 每次往下走有两个选择
   dfs(x + 1, y, sum + a[x][y]);  // 向正下方走
   dfs(x + 1, y + 1, sum + a[x][y]);  // 向右下方走
}
dfs(0,0);

猜你喜欢

转载自www.cnblogs.com/isguoqiang/p/11482132.html