514 Freedom Trail 自由之路

详见:https://leetcode.com/problems/freedom-trail/description/

C++:

class Solution {
public:
    int findRotateSteps(string ring, string key) 
    {
        int n = ring.size(), m = key.size();
        vector<vector<int>> dp(m + 1, vector<int>(n));
        for (int i = m - 1; i >= 0; --i)
        {
            for (int j = 0; j < n; ++j) 
            {
                dp[i][j] = INT_MAX;
                for (int k = 0; k < n; ++k)
                {
                    if (ring[k] == key[i])
                    {
                        int diff = abs(j - k);
                        int step = min(diff, n - diff);
                        dp[i][j] = min(dp[i][j], step + dp[i + 1][k]);
                    }
                }
            }
        }
        return dp[0][0] + m;      
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6675879.html

posted on 2018-04-22 16:19  lina2014  阅读(165)  评论(0编辑  收藏  举报

导航