leetcode 1320. Minimum Distance to Type a Word Using Two Fingers (dp O(N) Solution)

在这里插入图片描述
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.

设dis(a,b)为a移动到b的花费。对于只考虑一个手指的情况,很容易得到sum。这时考虑第二个手指移动能够节省的费用save,用sum-save即可得到最优值。
考虑now移动到to
dp[now],表示第二个手指头到当前位置能够达到的最大节省。
∑ 0 26 d p [ n o w ] = m a x ( d p [ n o w ] , d p [ i ] + d i s ( n o w , t o ) − d i s ( i , t o ) ) \sum_{0}^{26} dp[now] = max(dp[now],dp[i] + dis(now,to)-dis(i,to)) 026dp[now]=max(dp[now],dp[i]+dis(now,to)dis(i,to))
代码如下:

class Solution {
    
    
public:
    int getdis(const int &val1,const int &val2){
    
    
        const int b = 6;
        int x1 = val1/b;
        int y1 = val1%b;
        int x2 = val2/b;
        int y2 = val2%b;
        int dis = abs(x1-x2)+abs(y1-y2);
        return dis;
    }
    
    int minimumDistance(string word) {
    
    
        vector<int> dp(27,0);
        int len = word.size();
        int sum = 0,save = 0;
        for(int i=0;i<len-1;++i){
    
    
            int now = word[i]-'A';
            int to = word[i+1]-'A';
            sum += getdis(now,to);
            for(int j=0;j<26;++j){
    
    
                dp[now] = max(dp[now],dp[j]+(getdis(now,to)-getdis(j,to)));
            }
            save = max(save,dp[now]);
        }
        return sum-save;
    }
};

猜你喜欢

转载自blog.csdn.net/zhao5502169/article/details/104120452