2318. Number of Distinct Roll Sequences
Question
You are given an integer
n
. You roll a fair 6-sided dicen
times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
- The greatest common divisor of any adjacent values in the sequence is equal to
1
.- There is at least a gap of
2
rolls between equal valued rolls. More formally, if the value of thei<sup>th</sup>
roll is equal to the value of thej<sup>th</sup>
roll, thenabs(i - j) > 2
.Return the* total number** of distinct sequences possible*. Since the answer may be very large, return it modulo
10<sup>9</sup><span> </span>+ 7
.Two sequences are considered distinct if at least one element is different.
Solution
DFS+记忆化搜索剪枝。
辅助方法getValidNext计算前两个位置为last1和last2时的所有的下一个有效值,将返回值储存在next[][]数组中。
DFS搜索
DFS搜索,传入剩余骰子数量n,前两个骰子的值x和y。
从next[x][y]中得到所有有效值。并进行递归。
将返回结果加和并返回。
当n等于0时,只有一个组合,因此返回1。
记忆化搜索
在搜索时会重复计算很多相同的x,y与n的组合,因此可以采用记忆化搜索进行剪枝。
用memo[][][]数组记录x,y与n的状态。如果此前已经计算过其结果,则直接返回memo[x][y][n]。
Code
1 | class Solution { |
2318. Number of Distinct Roll Sequences
https://xuanhe95.github.io/2022/06/26/2318-Number-of-Distinct-Roll-Sequences/