深度优先搜索是一种遍历的方式,同时也是连接dp(动态规划)的桥梁
举个例子:
这是dfs和dp很经典的列题,为什么即是dfs也是dp,请看接下来题解
dfs解法(注:需要有一定递归基础)
#include <iostream>
int n,cnt=0;
void dfs(int x)
{
if (x == n) { //判断是否达到条件
cnt++;
return;
}
else if (x > n) { //若遍历的超出所给台阶数则直接返回不算次数
return;
}
//选择跳一个台阶
x += 1;
dfs(x);
x -= 1; //回溯
//选择跳两个台阶
x += 2;
dfs(x);
x -= 2; //回溯
}
int main()
{
std::cin >> n;
dfs(0); //深度优先搜索总数从0开始
std::cout << cnt << "\n";
return 0;
}
dp写法(注:dp难度极大无固定模板,每题解决方法都不同)
思路:若n为1 则有1种 1
若n为2 则有2种 1 1 或 2
若n为3 则有3种 1 1 1 或1 2 或2 1
若n为4 则有5种(太多懒得写)不难发现当n>=3时,an=a(n-1)+a(n-2);
则发现的此题的转换方程an=a(n-1)+a(n-2);
代码如下
#include <iostream>
int main()
{
int a[10000];
std::cin >> n;
a[1] = 1, a[2] = 2;
for (int i = 3; i <= n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
std::cout << a[n] << "\n";
return 0;
}
会发现dp相比dfs代码量减少的同时更高效;
© 版权声明
THE END
暂无评论内容