1. 程式人生 > >514 Freedom Trail 自由之路

514 Freedom Trail 自由之路

ring leetcode 參考 return des abs problem nbsp logs

詳見: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

514 Freedom Trail 自由之路