(nice!!!)(LeetCode 每日一题) 808. 分汤 (深度优先搜索dfs)
题目:808. 分汤
思路:深度优先搜索dfs+记忆化搜索,时间复杂度0(n*n)。这里的n最大为400。
C++版本:
class Solution {
public:double dfs(int x,int y,vector<vector<double>> &sta){// 平手if(x<=0 && y<=0) return 0.5;// A先耗尽if(x<=0) return 1;// B先耗尽if(y<=0) return 0;// 之前遍历过if(sta[x][y]!=0) return sta[x][y];// 记忆化sta[x][y]=0.25*(dfs(x-4,y,sta)+dfs(x-3,y-1,sta)+dfs(x-2,y-2,sta)+dfs(x-1,y-3,sta));return sta[x][y];}double soupServings(int n) {// 大于10000为1可以传n为10000进去,输出的结果ans与1的误差小于10^-5if(n>=10000) return 1;// 都是25的整数倍,在记忆化时,很多位置都没有用到,所以都除以25n=(n+24)/25;// 记忆化数组,避免重复遍历vector<vector<double>> sta(n+1,vector<double>(n+1));// 深度优先搜索dfsreturn dfs(n,n,sta);}
};
JAVA版本:
class Solution {double dfs(int x,int y,double[][] sta){if(x<=0 && y<=0) return 0.5;if(x<=0) return 1;if(y<=0) return 0;if(sta[x][y]!=0) return sta[x][y];sta[x][y]=0.25*(dfs(x-4,y,sta)+dfs(x-3,y-1,sta)+dfs(x-2,y-2,sta)+dfs(x-1,y-3,sta));return sta[x][y];}public double soupServings(int n) {if(n>=10000) return 1;n=(n+24)/25;double[][] sta=new double[n+1][n+1];return dfs(n,n,sta);}
}
GO版本:
func soupServings(n int) float64 {if n>10000 {return 1}n=(n+24)/25sta:=make([][]float64,n+1)for i:=range sta {sta[i]=make([]float64,n+1)}return dfs(n,n,sta)
}func dfs(x,y int,sta [][]float64) float64 {if x<=0&&y<=0 {return 0.5}if x<=0 {return 1}if y<=0 {return 0}if sta[x][y]!=0 {return sta[x][y]}sta[x][y]=0.25*(dfs(x-4,y,sta)+dfs(x-3,y-1,sta)+dfs(x-2,y-2,sta)+dfs(x-1,y-3,sta))return sta[x][y]
}