920. Number of Music Playlists
Đề Bài
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
- Every song is played at least once.
- A song can only be played again only if
kother songs have been played.
Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: n = 3, goal = 3, k = 1 Output: 6 Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].
Example 2:
Input: n = 2, goal = 3, k = 0 Output: 6 Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].
Example 3:
Input: n = 2, goal = 3, k = 1 Output: 2 Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].
Constraints:
0 <= k < n <= goal <= 100
Thuật Toán & Kỹ Thuật
⏱️ Thời gian
O(n)
💾 Không gian
O(n)
Lời Giải
C++
0920-number-of-music-playlists.cpp
int memo[101][101];
const int MOD = 1e9 + 7;
class Solution {
private:
int n, k;
public:
int dp(int old_song, int goal) {
if (goal == 0) {
return old_song == n;
}
if (memo[old_song][goal] != -1) {
return memo[old_song][goal];
}
long long ans = (1LL*dp(old_song + 1, goal - 1) * max(n - old_song, 0)) % MOD;
ans = (ans + 1LL*dp(old_song, goal - 1) * max(old_song - k, 0)) % MOD;
return memo[old_song][goal] = ans;
}
int numMusicPlaylists(int n, int goal, int k) {
memset(memo, -1, sizeof(memo));
this->n = n;
this->k = k;
return dp(0, goal);
}
};