题意:
Bob 站在单元格 (0, 0)
,想要前往目的地 destination
:(row, column)
。他只能向 右 或向 下 走。你可以为 Bob 提供导航 指令 来帮助他到达目的地 destination
。
指令 用字符串表示,其中每个字符:
'H'
,意味着水平向右移动'V'
,意味着竖直向下移动
能够为 Bob 导航到目的地 destination
的指令可以有多种,例如,如果目的地 destination
是 (2, 3)
,"HHHVV"
和 "HVHVH"
都是有效 指令 。
然而,Bob 很挑剔。因为他的幸运数字是 k
,他想要遵循 按字典序排列后的第 k
条最小指令 的导航前往目的地 destination
。k
的编号 从 1 开始 。
给你一个整数数组 destination
和一个整数 k
,请你返回可以为 Bob 提供前往目的地 destination
导航的 按字典序排列后的第 k
条最小指令
解题思路:
二分法查询当前位置应该向下走还是向右走
const int maxn = 35;
long long C[maxn][maxn];
class Solution {
public:
string kthSmallestPath(vector<int>& dest, int k) {
C[0][0] = 1;
for(int i = 1; i < maxn; i++) {
C[i][0] = C[i][i] = 1;
for(int j = 1; j < maxn; j++) {
C[i][j] = C[i-1][j-1] + C[i-1][j];
}
}
int m = dest[0], n = dest[1];
string ans = "";
for(int i = 1, lim = n + m; i <= lim; i++) {
if(n >= 1 && C[n-1+m][m] >= k) {
ans += 'H'; n--;
} else {
ans += 'V';
k -= C[n-1+m][m];
m -= 1;
}
}
return ans;
}
};