1320.Minimum-Distance-to-Type-a-Word-Using-Two-Fingers
1320. Minimum Distance to Type a Word Using Two Fingers
题目地址
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/
https://www.acwing.com/file_system/file/content/whole/index/content/304924/
题目描述
You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).
代码
Approach #1 3D DP
Let dp[i][j][k] be the minimum distance to build the substring from word from index i untill the end of the word, given that currently the fingers are on positions j and k respectively.
The transition function will be:
Then all we need to do is return dp[0][26][26], since both fingers start with no position.
Time: O(n⋅26⋅26) && Space: O(n⋅26⋅26)
初始化任意两个字母的距离。 设状态 f(i,j,k)f(i,j,k) 表示当前完成了前 i 个字母,当前第一根手指在字母 j 上,第二根手指在字母 kk 上的最少步数。 初始时,f(0,j,k)=0f(0,j,k)=0,其余为正无穷。初始状态表示了,还没有进行任何操作时,两根手指在任意位置的花费都是 0。 转移时,有两种情况,假设上一次手指的位置为 j 和 k,待移动到的字母为 t。第一种是移动第一根手指,则 f(i,t,k)=min(f(i,t,k),f(i−1,j,k)+dis(j,t)f(i,t,k)=min(f(i,t,k),f(i−1,j,k)+dis(j,t) 第二种是移动第二根手指,则 f(i,j,t)=min(f(i,j,t),f(i−1,j,k)+dis(k,t)f(i,j,t)=min(f(i,j,t),f(i−1,j,k)+dis(k,t) 最终答案为 min(f(n,j,k))min(f(n,j,k))
Approach #2 1D DP
Last updated
Was this helpful?