力扣1643题解:贪心算法与组合数的完美结合
一、问题理解
我们需要构造从起点到终点的路径指令,满足:
只能向右或向下移动
所有可能路径按字典序排列
找到第k小的路径指令
二、算法设计思路
三、实现代码
class Solution { public: string kthSmallestPath(vector<int>& destination, int k) { int v = destination[0]; // 需要向下走的次数 int h = destination[1]; // 需要向右走的次数 string res; // 预计算组合数C(n,k) vector<vector<int>> comb(h + v, vector<int>(h + v, 0)); for (int i = 0; i < h + v; ++i) { comb[i][0] = 1; for (int j = 1; j <= i; ++j) { comb[i][j] = comb[i-1][j-1] + comb[i-1][j]; } } while (h > 0 && v > 0) { // 如果选择'H',后面有C(h+v-1, h-1)种可能 int c = comb[h + v - 1][h - 1]; if (k <= c) { res += 'H'; h--; } else { res += 'V'; k -= c; v--; } } // 处理剩余全部'H'或'V'的情况 res += string(h, 'H'); res += string(v, 'V'); return res; } };
四、关键实现细节
原创内容 转载请注明出处