记忆化搜索题目总结(1)
一. 概述
算法上依然是搜索的流程,但是搜索到的一些解用动态规划的那种思想和模式作一些保存。在求解的时候还是按着自顶向下的顺序,但是每求解一个状态,就将它的解保存下来,以后再次遇到这个状态的时候,就不必重新求解了。这种方法综合了搜索和动态规划两方面的优点。
二. 引题
POJ1579 题目链接
if a <= 0 or b <= 0 or c <= 0, then w(a, b, c) returns 1
if a > 20 or b > 20 or c > 20, then w(a, b, c) returns w(20, 20, 20)
if a < b and b < c, then w(a, b, c) returnsw(a, b, c-1) + w(a, b-1, c-1) - w(a, b-1, c)
otherwise it returns w(a-1, b, c) + w(a-1, b-1, c) + w(a-1, b, c-1) - w(a-1, b-1, c-1)
DFS做法
long long dfs(int x, int y, int z)
{
if(x <= 0 || y <= 0 || z <= 0){
return 1;
}
if(x > 20 || y > 20 || z > 20){
x = y = z = 20;
}
if(x < y && y < z){
return dfs(x, y, z - 1) + dfs(x, y - 1, z - 1) - dfs(x, y - 1, z);
}
else{
return dfs(x - 1, y, z) + dfs(x - 1, y - 1, z) + dfs(x - 1, y, z - 1) - dfs(x - 1, y - 1, z - 1);
}
}
上述的dfs做法可以发现计算了大量的重叠子问题,如在计算dfs(4, 4, 4)和dfs(3, 4, 5)时都需要计算dfs(3, 4, 4),都会遍历dfs(3, 4, 4)这整颗子树,花费大量时间,因此我们想到将每个状态的值记录下来,以后求解时可以直接得到该值。
记忆化搜索解法
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
long long dp[21][21][21];
long long dfs(int x, int y, int z)
{
if(x <= 0 || y <= 0 || z <= 0){
return 1;
}
if(dp[x][y][z]){
return dp[x][y][z];
}
if(x < y && y < z){
dp[x][y][z] = dfs(x, y, z - 1)