[Leetcode] 514. Freedom Trail 解题报告

该博客详细介绍了Leetcode中的514题——'Freedom Trail'的解题过程。玩家需旋转金属圆盘以拼写出特定关键词来解锁门。博主分析了题意,提出将问题转化为动态规划(DP)问题,以找到拼写所有关键字字符所需的最小步数。定义了dp[i][j]表示拼写到key的第i个字符,终点为第j个候选字符的最短路径,并给出了递推公式。通过滚动数组进一步优化空间复杂度,最后展示了代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.

Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.

Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button. 
At the stage of rotating the ring to spell the key character key[i]:
  1. You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].
  2. If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.

Example:


Input: ring = "godding", key = "gd"
Output: 4
Explanation:
For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
Also, we need 1 more step for spelling.
So the final output is 4.

Note:

  1. Length of both ring and key will be in range 1 to 100.
  2. There are only lowercase letters in both strings and might be some duplcate characters in both strings.
  3. It's guaranteed that string key could always be spelled by rotating the string ring.

思路

感觉这道题目的难点在于对题目的理解以及将它适当地转化为DP问题(当然用DFS也可以解决,但我还是喜欢DP代码的简洁和优雅)。

定义dp[i][j] = {index, length}表示从key中的第0个字符按到第i个字符,如果终点是其第j个候选者,所需要的最短路径。例如对于key = “gd”而言,d和g都分别有两个候选字符。我们将index也放在dp里面是因为如果有了index,就可以直接构造递推公式:dp[i][j].second = min(dp[i-1][k].second + length(dp[i-1][k] to dp[i][j])) + 1,而dp[i][j].first即为第j个候选字符所在的位置。在上面的递推公式中,计算length(dp[i-1][k] to dp[i][j])就会用到dp[i-1][k].first和dp[i][j].first。最后返回dp[key.size() - 1][j].second中的最小值即可。

从上面的递推公式可以看出,dp[i][j]只和dp[i-1][k]有关系,所以我们可以利用滚动法进一步将空间复杂度从O(mn)降低到O(m),其中n是key的长度,m是key中的字符在ring中的最大出现次数。

代码

class Solution {
public:
    int findRotateSteps(string ring, string key) {
        int size = ring.size();
        unordered_map<char, vector<int>> hash;     // {character, indices}
        vector<pair<int, int>>  dp = {{0, 0}};     // {index, length}
        for (int i = 0; i < size; ++i) {
            hash[ring[i]].push_back(i);
        }
        for (int i = 0; i < key.size(); ++i) {
            const vector<int> &dest_indices = hash[key[i]];
            vector<pair<int, int>> new_dp;
            for (int j = 0; j < dest_indices.size(); ++j) {
                int min_length = INT_MAX;
                for (int k = 0; k < dp.size(); ++k) {
                    int start = dp[k].first, end = dest_indices[j];
                    int length = dp[k].second + getLength(start, end, size);
                    if (length < min_length) {
                        min_length = length;
                    }
                }
                new_dp.push_back(make_pair(dest_indices[j], min_length + 1));
            }
            dp = new_dp;
        }
        int min_length = INT_MAX;
        for (auto p : dp) {
            min_length = min(min_length, p.second);
        }
        return min_length;
    }
private:
    int getLength(int start, int end, int size) {
        if (start > end) {          // get the length from start to end (int two directions)
            swap(start, end);
        }
        return min(end - start, size - end + start);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值