Skip to content

Commit 372e1c8

Browse files
Create 1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.java
1 parent 0af425f commit 372e1c8

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/* Top-Down Approach
2+
-------------------------------------
3+
Time Complexity: O(n*min(n,m))
4+
Space Complexity: O(n*min(n,m))
5+
------------------------------------*/
6+
class Solution {
7+
Map<String, Integer> memo;
8+
int MOD = (int)1e9+7;
9+
public int numWays(int steps, int arrLen){
10+
memo = new HashMap<>();
11+
return dfs(0, steps, arrLen);
12+
}
13+
private int dfs(int i, int steps, int n){
14+
String pos = i + "," + steps;
15+
if(memo.containsKey(pos))
16+
return memo.get(pos);
17+
if(steps == 0 && i == 0)
18+
return 1;
19+
if(i < 0 || i > n-1 || steps == 0)
20+
return 0;
21+
22+
long left = dfs(i-1, steps-1, n);
23+
long stay = dfs(i, steps-1, n);
24+
long right = dfs(i+1, steps-1, n);
25+
int res = (int)((left + stay + right)%MOD);
26+
memo.put(pos, res);
27+
return res;
28+
}
29+
}
30+
31+
/* Bottom-Up Approach
32+
------------------------------------
33+
Time Complexity: O(n*min(n,m))
34+
Space Complexity: O(n*min(n,m))
35+
-----------------------------------*/
36+
class Solution {
37+
public int numWays(int steps, int arrLen) {
38+
int MOD = (int)1e9+7;
39+
arrLen = Math.min(arrLen, steps);
40+
int[][] dp = new int[steps + 1][arrLen];
41+
42+
dp[0][0] = 1;
43+
44+
for (int step = 1; step <= steps; step++) {
45+
for (int pos = 0; pos < arrLen; pos++) {
46+
dp[step][pos] = dp[step - 1][pos];
47+
48+
if (pos - 1 >= 0) {
49+
dp[step][pos] = (dp[step][pos] + dp[step - 1][pos - 1]) % MOD;
50+
}
51+
if (pos + 1 < arrLen) {
52+
dp[step][pos] = (dp[step][pos] + dp[step - 1][pos + 1]) % MOD;
53+
}
54+
}
55+
}
56+
57+
return dp[steps][0];
58+
}
59+
}

0 commit comments

Comments
 (0)