Dice Combinations(Dynamic Programming)
题目描述
Your task is to count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.
For example, if n=3, there are 4 ways:
1+1+1
1+2
2+1
3
输入
The only input line has an integer n.
Constraints
1 ≤ n ≤
输出
Print the number of ways modulo .
样例输入
3
样例输出
4
思路分析
动态规划,类似于爬楼梯。
n 0 1 2 3 4 5 6 7 8 dp[n] 1 1 2 4 8 16 32 63 125 每次掷骰子,可以得到1~6中任意一个数字,所以状态转移方程为:dp[n]=dp[n-1]+dp[n-2]+dp[n-3]+dp[n-4]+dp[n-5]+dp[n-6]。其中n-i<0时,dp[n-i]=0;dp[0]=1。
假设我们现在正在爬楼梯,一个六面骰子掷到哪个数,就爬几个台阶。想要到达第八层台阶,可以在第2层台阶掷出数字6,也可以在第3层台阶掷出数字5,在第4层台阶掷出数字4,在第5层台阶掷出数字3,在第6层台阶掷出数字2,可以在第7层台阶掷出数字1。这样看来,一共有六种方法可以实现到达第八层台阶,即dp[8]=dp[7]+dp[6]+dp[5]+dp[4]+dp[3]+dp[2]。
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod=1e9+7;
ll n;
int main(){cin>>n;vector<ll>dp(n+1,0);dp[0]=1;for(ll i=1;i<=n;i++){for(int j=1;j<=6;j++){if(i-j>=0){dp[i]=(dp[i]+dp[i-j])%mod;}}}cout<<dp[n];return 0;
}