Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is either:
'H', meaning move horizontally (go right), or
'V', meaning move vertically (go down).
Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the kthlexicographically smallest instructions that will lead him to destination. k is 1-indexed.
Given an integer array destination and an integer k, return thekthlexicographically smallest instructions that will take Bob todestination.
Input: destination =[2,3], k =1Output: "HHHVV"Explanation: All the instructions that reach(2,3)in lexicographic order are as follows:["HHHVV","HHVHV","HHVVH","HVHHV","HVHVH","HVVHH","VHHHV","VHHVH","VHVHH","VVHHH"].
At each step, decide whether to use ‘H’ or ‘V’ by counting the number of possible instructions starting with ‘H’. If k is greater than that, use ‘V’ and decrease k accordingly.
Precompute binomial coefficients for all possible values.
For each position, if the number of instructions starting with ‘H’ is at least k, append ‘H’ and decrease the number of columns; otherwise, append ‘V’, decrease k, and decrease the number of rows.
classSolution {
funkthSmallestPath(destination: IntArray, k: Int): String {
var row = destination[0]
var col = destination[1]
val comb = Array(row+col+1) { IntArray(col+1) }
for (i in0..row+col) {
comb[i][0] = 1; comb[i][i] = 1for (j in1 until i)
comb[i][j] = comb[i-1][j-1] + comb[i-1][j]
}
val res = StringBuilder()
for (i in0 until row+col) {
if (col > 0) {
val cnt = comb[row+col-1-i][col-1]
if (k <= cnt) {
res.append('H'); col-- } else {
res.append('V'); k -= cnt; row-- }
} else {
res.append('V'); row-- }
}
return res.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defkthSmallestPath(self, destination: list[int], k: int) -> str:
from math import comb
row, col = destination
res = []
for _ in range(row + col):
if col >0:
cnt = comb(row + col -1, col -1)
if k <= cnt:
res.append('H')
col -=1else:
res.append('V')
k -= cnt
row -=1else:
res.append('V')
row -=1return''.join(res)