LeetCode #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

class Solution {
public:
    int numMusicPlaylists(int N, int L, int K) {
        vector<vector<long long>> dp(N+1,vector<long long>(L+1,0));
        long long x=pow(10,9)+7;
        dp[1][1]=1; //dp[n][l]表示用n首歌产生一个符合要求的长度为l的歌单的所有可能情况
        //初始化dp第一行和第一列,第一列表示n>=1,l=1,显然错误,所以第一列除dp[1][1]全部为0
        if(K==0) //第一行表示n=1,l>=1,只有K=0时,第一行才为1
            for(int l=2;l<=L;l++) dp[1][l]=1;
        for(int n=2;n<=N;n++)
        {
            for(int l=n;l<=L;l++)
            {   //dp[n][l]=dp[n-1][l-1]*n+dp[n][l-1]*(n-K)
                //当只用n-1首歌产生了长度为l-1的歌单时,余下的那首歌有n种可能
                dp[n][l]+=dp[n-1][l-1]*n;
                if(n>K) dp[n][l]+=dp[n][l-1]*(n-K);
                dp[n][l]%=x;
            }
        }
        return dp[N][L];
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值