Project Euler 164
Project Euler 164
题目
Numbers for which no three consecutive digits have a sum greater than a given value
How many $20$ digit numbers $n$ (without any leading zero) exist such that no three consecutive digits of $n$ have a sum greater than $9$?
解决方案
本题是一个明显的数位动态规划。
令$f(i,a,b)(i\ge 1,0\le a+b\le 9)$为目前符合题意的$i$位数中,个位为$b$,十位为$a$的数的个数,为了保证添加连续三个数的和不超过$9$,那么个位后面添加的数必须不超过$9-a-b$。
那么可以得到状态转移方程:
由于只有一位数时,十位为$0$,因此只要求$b>0$。而且,为了防止以后出现前导$0$,$f(1,0,0)=0$。
代码
1 |
|