leetcode 1320

问题

img

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).

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|.

Note that the initial positions of your two fingers are considered free so don’t count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

Example 1:

1
2
3
4
5
6
7
8
9
Input: word = "CAKE"
Output: 3
Explanation:
Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3

Example 2:

1
2
3
4
5
6
7
8
9
10
Input: word = "HAPPY"
Output: 6
Explanation:
Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6

Example 3:

1
2
Input: word = "NEW"
Output: 3

Example 4:

1
2
Input: word = "YEAR"
Output: 7

Constraints:

  • 2 <= word.length <= 300
  • Each word[i] is an English uppercase letter.

分析

保留了DFS的每个状态从而改进为了DP。要总结一下通过DFS优化得到DP的题目。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int dp[300][27][27];
int minimumDistance(string word) {
memset(dp, -1, sizeof(dp));
return dfs(word, 0, 26, 26);
}
int cost(int finger, int t) {
if (finger == 26) return 0;
int x0 = finger/6;
int y0 = finger%6;
int x1 = t/6;
int y1 = t%6;
return abs(x0-x1)+abs(y0-y1);
}
// 当前左手在哪里,当前右手在哪里,接下来要按第几个字符
// 比较左手去按,还是右手去按哪个更小
int dfs(const string &s, int index, int left, int right) {
if (index >= s.size())
return 0;
if (dp[index][left][right] > 0)
return dp[index][left][right];
int num = s[index]-'A';
int l = cost(left, num) + dfs(s, index+1, num, right);
int r = cost(right, num) + dfs(s, index+1, left, num);
return dp[index][left][right] = min(l, r);
}
};