[LeetCode] Number of Ways to Rearrange Sticks With K Sticks Visible

1866. Number of Ways to Rearrange Sticks With K Sticks Visible

There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.

  • For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.

Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
int dp[1001][1001];
int mod = 1e9 + 7;
public:
long rearrangeSticks(int n, int k) {
if(n == k) return 1;
if(!k) return 0;
if(!dp[n][k]) {
return dp[n][k] = (rearrangeSticks(n - 1, k - 1) + rearrangeSticks(n - 1, k) * (n - 1))%mod;
}
return dp[n][k];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.