题意:
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;
}
};

本文介绍了一种使用二分法确定机器人Bob前往指定目的地时,按字典序排列的第K条最小路径指令的方法。通过预先计算组合数,该算法能够在每一步决定是水平移动还是垂直移动。
706

被折叠的 条评论
为什么被折叠?



