题目描述
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:
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:
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:
Input: word = "NEW"
Output: 3
Example 4:
Input: word = "YEAR"
Output: 7
Constraints:
2 <= word.length <= 300
Each word[i] is an English uppercase letter.
思路
思路1:记忆化搜索,三维时,可以表示当前搜索到的字符和两个手指分别的位置。因为肯定有一个手指在上一个字符处,所以可以压缩到二维。返回的是从i 到n 的最小代价。
思路2:动态规划,bottom to up,dp[i][j] 表示打印完前 i 个字符,一个手指在位置 j 处,花费的最小代价。状态转移,dp[i] 遍历另一个手指的所有位置push到dp[i+1]状态。
代码
思路1:
class Solution {
public:
int cost (int i, int j) {
if (i == 26) return 0;
return abs(i/6 - j/6) + abs(i%6 - j%6);
}
int minimumDistance(string word) {
vector<vector<int> > mem(word.size(), vector<int> (27));
int hang = 26;
return dp(0, hang, word, mem);
}
int dp(int i, int o, string word, vector<vector<int> >& mem) {
if (i == word.size()) return 0;
if (mem[i][o]) return mem[i][o];
int p = (i == 0) ? 26 : word[i-1] - 'A';
int c = word[i] - 'A';
return mem[i][o] = min(dp(i+1, o, word, mem)+cost(p, c), dp(i+1, p, word, mem)+cost(o, c));
}
};
思路2:
class Solution {
public:
int cost (int i, int j) {
if (i == 26) return 0;
return abs(i/6 - j/6) + abs(i%6 - j%6);
}
int minimumDistance(string word) {
int n = word.size();
vector<vector<int> > dp(n+1, vector<int>(27, INT_MAX/2));
dp[0][26] = 0;
for (int i=0; i<n; ++i) {
int p = (i == 0) ? 26 : word[i-1] - 'A';
int c = word[i] - 'A';
for (int j=0; j<27; ++j) {
dp[i+1][p] = min(dp[i+1][p], dp[i][j] + cost(j, c));
dp[i+1][j] = min(dp[i+1][j], dp[i][j] + cost(p, c));
}
}
return *min_element(dp[n].begin(), dp[n].end());
}
};