920. Number of Music Playlists
阿新 • • 發佈:2018-12-13
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:
0 <= K < N <= L <= 100
思路: 如果先去掉 每首歌必須放一次 這個限制,用DP,dp[i]=dp[i-1]*(n-K)
如果加上這個限制,dp[n][l]表示已經聽過了n首歌,一共放了l首歌的總數,dp[n][l]=dp[n-1][l-1]*n+dp[n][l-1]*(n-K)
class Solution(object): def numMusicPlaylists(self, N, L, K): """ :type N: int :type L: int :type K: int :rtype: int """ mod=10**9+7 if N==0 or L==0: return 0 #dp[n][l]: already use N with length l #dp[n][l]=dp[n-1][l-1]*n+dp[n][l-1]*(n-k) dp=[[0 for _ in range(L+1)] for _ in range(1+N)] dp[1][1]=1 if K==0: for i in range(2,L+1): dp[1][i]=1 for i in range(2,N+1): for j in range(1,L+1): dp[i][j]=dp[i-1][j-1]*i if i-K>0: dp[i][j]+=dp[i][j-1]*(i-K) dp[i][j]%=mod return dp[N][L]%mod s=Solution() print(s.numMusicPlaylists(N = 3, L = 3, K = 1)) print(s.numMusicPlaylists(N = 2, L = 3, K = 0)) print(s.numMusicPlaylists(N = 2, L = 3, K = 1))