dfs与dp算法之关系与经典入门例题
声明
本文不介绍dfs、dp算法的基础思路,有想了解的可以自己找资源学习。
本文适合于刚刚接触dfs和dp算法的人,发现两种算法间的内在联系。
本人算法之路走之甚短,如果理解出现问题欢迎大家的指正,我会分享基于我目前理解到的算法思想。
dfs与dp的关系
很多情况下,dfs和dp两种解题方法的思路都是很相似的,这两种算法在一定程度上是可以互相转化的。
想到dfs也就常常会想到dp,当然在一些特定的适用场合下除外。
dp主要运用了预处理的思想,而dfs则是类似于白手起家,一步步探索。一般来讲,能够预处理要好些,好比战争前做好准备。
dfs和dp都是十分重要的基础算法,在各个竞赛中都有涉及,务必精通。
经典例题-数字三角形 - POJ 1163
题目
The Triangle
Description
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
dfs思路
解题思路
自顶向下,将每种路径都走一遍。

通过迭代计算到最后一层,记录最后一层的所有值。
最后一层中的最大值即为所求。
具体代码
#include <iostream>
// use vector vessel to write down the final level
#include <vector>
// use 'sort' method in <algorithm>
#include <algorithm>
// use 'greater<T>' functional template in <functional>
#include <functional>
using namespace std;
// the maximum of the triangle ordinal
const int max_ordinal = 100;
// the depth
int num_of_rows;
// save data
int data[max_ordinal][max_ordinal];
// save the data of the final level
vector<int> ans;
void dfs(int level, int sum, int column)
{
// avoid multi calculate
int current_sum = sum+data[level][column];
// save data which was in final level
if(level+1 == num_of_rows)
{
ans.push_back(current_sum);
return;
}
// binary tree
dfs(level+1, current_sum, column);
dfs(level+1, current_sum, column+1);
}
int main()
{
cin >> num_of_rows;
for(int i = 0; i < num_of_rows; i++)
for(int j = 0; j <= i; j++)
scanf("%d", &data[i][j]);
dfs(0, 0, 0);
cout << "output data:" << endl;
sort(ans.begin(), ans.end(), greater<int>());
for(int i = 0; i < ans.size(); i++)
{
cout << ans[i] << "\t";
if(!((i+1) % 5)) cout << endl;
}
cout << endl;
return 0;
}
dp思路
解题思路
dfs的思路是从上到下,而dp的思路是:从第二层开始,每下去一次往回看一下并取上一层相邻两个大的那个。
具体代码
#include <iostream>
// use 'max' method and 'sort' method
#include <algorithm>
// use 'greater<T>' functional template
#include <functional>
using namespace std;
// same as DFS
const int max_ordinal = 100;
int num_of_rows;
int data[max_ordinal][max_ordinal];
// the array of the dp method
int dp[max_ordinal][max_ordinal];
int main()
{
cin >> num_of_rows;
for(int i = 0; i < num_of_rows; i++)
for(int j = 0; j<= i; j++)
scanf("%d", &data[i][j]);
// dp now
dp[0][0] = data[0][0];
for(int i = 1; i < num_of_rows; i++)
{
for(int j = 0; j <= i; j++)
{
if(j-1 >= 0)
{
dp[i][j] = data[i][j] + max(dp[i-1][j], dp[i-1][j-1]);
} else {
dp[i][j] = data[i][j] + dp[i-1][j];
}
}
}
// calling 'sort' method
sort(dp[num_of_rows-1], &dp[num_of_rows-1][num_of_rows], greater<int>());
for(int i = 0; i < num_of_rows; i++)
cout << dp[num_of_rows-1][i] << " ";
cout << endl;
cout << "answer is: ";
cout << dp[num_of_rows-1][0] << endl;
return 0;
}
dfs与dp算法之关系与经典入门例题的更多相关文章
- DFS与DP算法
名词解释: DFS(Dynamic Plan):动态规划 DFS(Depth First Search):深度优先搜索 DFS与DP的关系 很多情况下,dfs和dp两种解题方法的思路都是很相似的,这两 ...
- dp算法之硬币找零问题
题目:硬币找零 题目介绍:现在有面值1.3.5元三种硬币无限个,问组成n元的硬币的最小数目? 分析:现在假设n=10,画出状态分布图: 硬币编号 硬币面值p 1 1 2 3 3 5 编号i/n总数j ...
- POJ - 1330 Nearest Common Ancestors(dfs+ST在线算法|LCA倍增法)
1.输入树中的节点数N,输入树中的N-1条边.最后输入2个点,输出它们的最近公共祖先. 2.裸的最近公共祖先. 3. dfs+ST在线算法: /* LCA(POJ 1330) 在线算法 DFS+ST ...
- 图片大小以及dp和px关系一览表,logo尺寸
图片大小以及dp和px关系一览表 说明:根据上表,我们应该很容易算出一张图片在不同手机上的宽和高是多少. 结论 从上表可以得出如下结论 1. 图片放在drawable中,等同于放在drawable-m ...
- UvaLive6661 Equal Sum Sets dfs或dp
UvaLive6661 PDF题目 题意:让你用1~n中k个不同的数组成s,求有多少种组法. 题解: DFS或者DP或打表. 1.DFS 由于数据范围很小,直接dfs每种组法统计个数即可. //#pr ...
- 0-1背包的动态规划算法,部分背包的贪心算法和DP算法------算法导论
一.问题描述 0-1背包问题,部分背包问题.分别实现0-1背包的DP算法,部分背包的贪心算法和DP算法. 二.算法原理 (1)0-1背包的DP算法 0-1背包问题:有n件物品和一个容量为W的背包.第i ...
- 最大子段和的DP算法设计及其效率测试
表情包形象取自番剧<猫咪日常> 那我也整一个 曾几何时,笔者是个对算法这个概念漠不关心的人,由衷地感觉它就是一种和奥数一样华而不实的存在,即便不使用任何算法的思想我一样能写出能跑的程序 直 ...
- 华为笔试——C++平安果dp算法
题目:平安果 题目介绍:给出一个m*n的格子,每个格子里有一定数量的平安果,现在要求从左上角顶点(1,1)出发,每次走一格并拿走那一格的所有平安果,且只能向下或向右前进,最终到达右下角顶点(m,n), ...
- C++数字三角形问题与dp算法
题目:数字三角形 题目介绍:如图所示的数字三角形,要求从最上方顶点开始一步一步下到最底层,每一步必须下一层,求出所经过的数字的最大和. 输入:第一行值n,代表n行数值:后面的n行数据代表每一行的数字. ...
随机推荐
- Markdown  --> <img ... />
search \!\[(\w+)\]\(([a-zA-Z0-9/.]+)\) replace <img src="$2" width="30%"/>
- win10下cmd备注
要复制cmd里的字符串,右键选标记,选中待复制的字符串,ctrl+c 复制,ctrl+v粘贴内容(或者右键选择复制).这项操作支持复制cmd里的内容到其他地方,如txt里 win10之前cmd不支持c ...
- mybatis Invalid bound statement (not found)错误解决办法
由于新版的IntelliJ IDEA不再编译source folder下的xml文件,而我们平时使用mybatis时,习惯于将*Mapper.xml文件放在与dao层.service层平级的src目录 ...
- QTP中类的使用(转)
Call Test Class Tester Dim mvarTesterName,mvarAge,mvarGender Sub Class_Initia ...
- Ubuntu18.10 编译libevent出现错误: creating symbolic link XXXXXX : Operation not supported
今天在VirtualBox虚拟机下的Ubuntu18.10编译libevent源代码时,按照github中使用cmake方式: $ mkdir build && cd build $ ...
- MySQL分表备份
#!/bin/bash DUMP=/usr/bin/mysqldump MYSQL=/usr/bin/mysql IPADDR=127.0.0.1 PORT=3306 USER=abc PASSWD= ...
- python基础----求水仙花数
水仙花数,即一个三位数,各个位上的数字的三次方相加,等于该数本身.如:153 = 1**3 + 5 ** 3 + 3 ** 3 def is_narc_num(n): # if n <100 o ...
- 封装一个Js 对象 生成Json
<script src="~/Content/Scripts/jquery-1.11.3.min.js"></script> <script> ...
- WPF-将DataGrid控件中的数据导出到Excel
原文:WPF-将DataGrid控件中的数据导出到Excel 导出至Excel是非常常见,我们可以用很多类库,例如Aspose.NOPI.Interop,在这里我们使用微软自家的工具.我的WPF绑定的 ...
- ubuntu16.04安装docker11.09
1. 安装Docker 操作系统 ubuntu16.04 1.1. 配置源文件 $sudo apt-get update #允许 apt 命令 HTTPS 访问 Docker 源 $sudo ...
