<Data Structures and Algorithms> - Dynamic Planning Primer (1)

Dynamic programming is a problem-solving guidelines.

1. examples

  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. Analysis

1. According to the subject, depth-first search method may be employed.

Depth-first search, similar binary tree recursive algorithm, there are two strategies: divide and rule traversal.

  1. Takes a value traversing traverse, to be changed (here sum), dfs used as parameters of recursive functions during the transfer.
    Dfs defined here is to come to this point and the sum, this sum as a current change points down at (x, y), and therefore the sum of dfs as a parameter.
// 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);

Guess you like

Origin www.cnblogs.com/isguoqiang/p/11482132.html