-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0514-freedom-trail.js
37 lines (30 loc) · 983 Bytes
/
0514-freedom-trail.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 2D-DP
* Time O(n^2) | Space O(n^2)
* https://leetcode.com/problems/freedom-trail/
* @param {string} ring
* @param {string} key
* @return {number}
*/
var findRotateSteps = function(ring, key) {
const cache = {};
const dfs = (ringIdx, keyIdx) => {
const hash = `${ringIdx}-${keyIdx}`;
if (keyIdx === key.length) return 0;
if (cache[hash]) return cache[hash];
let min = Infinity;
for (let i = 0; i < ring.length; i++) {
if (ring[i] === key[keyIdx]) {
const clockOrAntiClockStep = Math.abs(i - ringIdx);
const complementOfClockOrAntiClockStep = ring.length - clockOrAntiClockStep;
min = Math.min(min,
1 + clockOrAntiClockStep + dfs(i, keyIdx+1),
1 + complementOfClockOrAntiClockStep + dfs(i, keyIdx+1)
);
}
}
cache[hash] = min;
return min;
}
return dfs(0,0);
};