leetcode-master/problems/0514.自由之路.md

43 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//dp[i][j]key的0~i位字符拼写后ring的第j位对齐1200方向需要的最小步数
//前提key[i] = ring[j]若不满足dp[i][j] = INT_MAX
这道题目我服! 没做出来
https://blog.csdn.net/qq_41855420/article/details/89058979
```
class Solution {
public:
int findRotateSteps(string ring, string key) {
//int dp[101][101] = {0};
int n = ring.size();
vector<vector<int>> dp(key.size() + 1, vector<int>(ring.size(), 0));
for (int i = key.size() - 1; i >= 0; i--) {
for (int j = 0; j < ring.size(); j++) {
dp[i][j] = INT_MAX;
for (int k = 0; k < ring.size(); 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]);
}
}
}
}
for (int i = 0; i < dp.size(); i++) {
for (int j = 0; j < dp[0].size(); j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}
return dp[0][0] + key.size();
}
};
```
2 3 4 5 5 4 3
2 1 0 0 1 2 3