Number of Ways to Stay in the Same Place After Some Steps LeetCode solution in Java

1
class Solution {
2

3
HashMap<String, Long> map = new HashMap();
4

5
public int numWays(int steps, int arrLen) {
6

7
return (int) (ways(steps, arrLen, 0) % ((Math.pow(10, 9)) + 7));
8
}
9

10
public long ways(int steps, int arrLen, int index) {
11
String curr = index + "->" + steps;
12

13
if (index == 0 && steps == 0) {
14
return 1;
15
} else if (index < 0 || (index >= arrLen) || steps == 0) {
16
return 0;
17
}
18

19
if (map.containsKey(curr)) {
20
return map.get(curr);
21
}
22
long stay = ways(steps - 1, arrLen, index);
23
long right = ways(steps - 1, arrLen, index + 1);
24
long left = ways(steps - 1, arrLen, index - 1);
25

26
map.put(curr, (stay + right + left) % 1000000007);
27

28
return (right + left + stay) % 1000000007;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0