You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md
+51
Original file line number
Diff line number
Diff line change
@@ -49,6 +49,24 @@ The visible sticks are underlined.
49
49
50
50
## Solutions
51
51
52
+
**Solution 1: Dynamic Programming**
53
+
54
+
We define $f[i][j]$ to represent the number of permutations of length $i$ in which exactly $j$ sticks can be seen. Initially, $f[0][0]=1$ and the rest $f[i][j]=0$. The answer is $f[n][k]$.
55
+
56
+
Consider whether the last stick can be seen. If it can be seen, it must be the longest. Then there are $i - 1$ sticks in front of it, and exactly $j - 1$ sticks can be seen, which is $f[i - 1][j - 1]$. If the last stick cannot be seen, it can be any one except the longest stick. Then there are $i - 1$ sticks in front of it, and exactly $j$ sticks can be seen, which is $f[i - 1][j] \times (i - 1)$.
We notice that $f[i][j]$ is only related to $f[i - 1][j - 1]$ and $f[i - 1][j]$, so we can use a one-dimensional array to optimize the space complexity.
67
+
68
+
The time complexity is $O(n \times k)$, and the space complexity is $O(k)$. Here, $n$ and $k$ are the two integers given in the problem.
69
+
52
70
<!-- tabs:start -->
53
71
54
72
### **Python3**
@@ -185,6 +203,39 @@ func rearrangeSticks(n int, k int) int {
185
203
}
186
204
```
187
205
206
+
### **TypeScript**
207
+
208
+
```ts
209
+
function rearrangeSticks(n:number, k:number):number {
0 commit comments