Leetcode 920. Number of Music Playlists

Problem:

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

 

Solution:

  这道题可以用动态规划解决,dp[i][j]表示用j首歌组成长度为i的playlist的可能性种类,对于dp[i][j]可以拆分成两部分,可以是第i个位置放新歌,新歌可能是N-j+1中的任意一首,也可以是第i个位置放老歌,可以放j-K中的一首,j-K要大于0。所以得到状态转移方程如代码中所示。此题代码量很小,但很难去思考这个问题。

Code:

 

 1 class Solution {
 2 public:
 3     int numMusicPlaylists(int N, int L, int K) {
 4         vector<vector<int64_t>> dp(L+1,vector<int64_t>(N+1,0));
 5         dp[0][0] = 1;
 6         for(int i = 1;i <= L;++i){
 7             for(int j = 1;j <= N;++j){
 8                 dp[i][j] = (dp[i-1][j-1]*(N-j+1)+dp[i-1][j]*max(j-K,0))%1000000007;
 9             }
10         }
11         return dp[L][N];
12     }
13 };

 

 

 

 

posted on 2019-01-06 14:01  周浩炜  阅读(446)  评论(0编辑  收藏  举报

导航