source: https://leetcode.com/problems/number-of-music-playlists/

## Table of Contents

### Number of Music Playlists

#### Description

Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will 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.

Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7.

#### Example 1:

**Input:** n = 3, goal = 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], and [3, 2, 1].

#### Example 2:

**Input:** n = 2, goal = 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], and [1, 2, 2].

#### Example 3:

**Input:** n = 2, goal = 3, k = 1**Output:** 2**Explanation:** There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].

#### Constraints:

- 0 <= k < n <= goal <= 100

#### Solution

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
class Solution { //let's you already have a list of i-1 songs //now to make it a list of i songs //you can either //- add a new unique song //- or you can replay an existing song public int numMusicPlaylists(int n, int goal, int k) { Long[][] memo = new Long[goal+1][n+1]; return (int)dfs(goal, n, k, n, memo); } //in a way i corresponds to the goal //and j corresponds to the total songs n available private static final int MOD = 1_000_000_007; private long dfs(int i, int j, int k, int n, Long[][] memo){ //base case //we have played each song atleast once //and we have achieved the goal if(i==0 && j==0){ return 1; } //1. we have achieved the goal but we haven't played each song atleast once //2. or we have played each song atleast once but haven't achieved the goal if(i==0 || j==0){ return 0; } if(memo[i][j]!=null) return memo[i][j]; //add a new unique song //you already have a list of i-1 songs //out of which j-1 is unique //if you add another unique song the length of the list would //become i and the total unique song in the list would become j //to add a unique song you can only choose it from the remaining //unique songs -> n - (j-1) long addAnUniqueSong = ((dfs(i-1, j-1, k, n, memo))%MOD * (n-j+1)%MOD)%MOD; //or you can replay an existing song //you already have a list of i-1 songs //out of which j is unique //if you want to replay an existing song //you can choose it from list of j-k songs //but you can only do it if j > k long replayAnExistingSong = 0; if(j>k) replayAnExistingSong = ((dfs(i-1, j, k, n, memo))%MOD * (j-k)%MOD)%MOD; //total songs played memo[i][j] = (addAnUniqueSong + replayAnExistingSong)%MOD; return memo[i][j]; } } |