[LeetCode] Kth Smallest Instructions

1643. Kth Smallest Instructions

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 kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.

Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int choice[16][16];
int getChoice(int h, int v) {
if(!v) return 1;
if(!h) return 1;
if(choice[h][v] != -1) return choice[h][v];
return choice[h][v] = getChoice(h-1,v) + getChoice(h, v-1);
}
string helper(int h, int v, int k) {
if(h == 0) return string(v,'V');
if(v == 0) return string(h, 'H');
if(getChoice(h-1,v) >= k)
return "H" + helper(h-1,v,k);
else return "V" + helper(h,v-1,k-getChoice(h-1,v));
}
public:
string kthSmallestPath(vector<int>& destination, int k) {
int h = destination[1], v = destination[0];
memset(choice,-1,sizeof(choice));
return helper(h,v,k);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/01/PS/LeetCode/kth-smallest-instructions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.