920. Number of Music Playlists

87 篇文章 0 订阅

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

思路: 如果先去掉 每首歌必须放一次  这个限制,用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)

ref:https://leetcode.com/problems/number-of-music-playlists/discuss/178415/C++JavaPython-DP-Solution

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值