用 f[i][j] 表示投了 i 次投骰子得到点数总和,从而得到状态转移方程 f[i][j]=f[i−1][j]+f[i−1][j−1]+⋯+f[i−1][j−min(k−1,j)] 。
class Solution {
public:
int numRollsToTarget(int n, int k, int target) {
const int MOD = 1e9 + 7;
vector<int> f(target + 1, 0);
f[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = target; j >= 0; --j) {
f[j] = 0;
for (int x = 1; x <= k && x <= j; ++x)
f[j] = (f[j] + f[j - x]) % MOD;
}
}
return f[target];
}
};
满足条件就排出前面的元素,保证满足条件的窗口,然后求解每回窗口坐标的最小值。
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size(), sum = 0, ans = 0x3f3f3f3f;
for (int i = 0, j = 0; i < n; ++i) {
sum += nums[i];
while (j < n && sum >= target) {
ans = min(ans, i - j + 1);
sum -= nums[j++];
}
}
return ans == 0x3f3f3f3f ? 0 : ans;
}
};