3446. 骰子点数之和问题
剑指 Offer 60. n个骰子的点数
逆推:
#include<bits/stdc++.h>
using namespace std;
const int MAXN=10000;
long double p=1.0/6.0;
int main() {
int n, k;
scanf("%d %d", &n, &k); //n个骰子 掷出和为k的概率
vector<vector<double>>dp(n+1,vector<double>(MAXN));
if(k>n*6 || k<n) {cout<<0; return 0;}
for(int j=1;j<=6;++j) dp[1][j]=p; //一个骰子组合初始化
for(int i=2;i<=n;i++){
for(int j=k;j>=i;--j){ //dp[i][j]为i个骰子情况下掷出j的组合数
int toplimit=min(j,6); //满足点数和为j时,第i个骰子掷出的点数可能为1-toplimit
for(int t=1;t<=toplimit;++t){ //t为第i个骰子掷出的数
dp[i][j]+=dp[i-1][j-t]*p;
}
}
}
printf("%.6f\n", dp[n][k]);
system("pause");
return 0;
}