920. Number of Music Playlists

Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that:

  • Every song is played at least once
  • A song can only be played again only if K other songs have been played

Return the number of possible playlists.  As the answer can be very large, return it modulo 10^9 + 7.

 

Example 1:

Input: N = 3, L = 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], [3, 2, 1].

Example 2:

Input: N = 2, L = 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], [1, 2, 2]

Example 3:

Input: N = 2, L = 3, K = 1
Output: 2
Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]

 

Note:

  1. 0 <= K < N <= L <= 100

思路:設i爲目前歌單的長度,j爲已聽歌曲數(不重複的數目),dp[i][j]爲排列的方案數,最終求dp[L][N]。

           1)若將要聽的下一首歌爲新歌,那麼狀態轉移方程爲:dp[i][j] = dp[i-1][j-1]*(N-(j-1))

           2)  若將要聽的下一首歌爲舊歌,且目前已聽歌曲數(不重複的數目)>=k,那麼就可以選取舊歌了,此時狀態轉移方程爲:dp[i][j] = dp[i-1][j-1]*(N-(j-1)) + dp[i-1][j]*(j-k)

注意dp[0][0]=1

class Solution {
public:
    const long long MOD = (long long) (1e9+7);
    int numMusicPlaylists(int N, int L, int K) {
        long long dp[104][104] = {};
        dp[0][0]=1;
        for(int i=1;i<=L;i++){
            for(int j=1;j<=N;j++){
                dp[i][j] = (dp[i-1][j-1]*(N-(j-1))) % MOD;
                if(j>=K){
                    //注意dp[i][j] += dp[i-1][j]*(j-K)) % MOD 會溢出,還是分開寫吧
                    dp[i][j] = (dp[i][j]+(dp[i-1][j]*(j-K)) % MOD) % MOD;
                }
            }
        }
        return (int)dp[L][N];
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章