-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1269. Number of Ways to Stay in the Same Place After Some Steps.java
77 lines (64 loc) · 1.97 KB
/
1269. Number of Ways to Stay in the Same Place After Some Steps.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Brute Force : TLE (time : exponential)
class Solution {
int mod=1000000007;
public int numWays(int steps, int arrLen) {
return solve(0,steps,arrLen)%mod;
}
int solve(int ind,int s,int a){
if(ind<0 || ind>=a)return 0;
if(ind==0 && s==0)return 1;
if(s==0)return 0;
int same_pos=solve(ind,s-1,a)%mod;
int left=solve(ind-1,s-1,a)%mod;
int right=solve(ind+1,s-1,a)%mod;
return (same_pos+left+right)%mod;
}
}
Memoization + DP (memori exeded)
class Solution {
int mod=1000000007;
int dp[][];
public int numWays(int steps, int arrLen) {
dp=new int[arrLen+1][steps+1];
for(int i=0;i<dp.length;i++){
Arrays.fill(dp[i],-1);
}
return solve(0,steps,arrLen)%mod;
}
int solve(int ind,int s,int a){
if(ind<0 || ind>=a)return 0;
if(ind==0 && s==0)return 1;
if(s==0)return 0;
if(dp[ind][s]!=-1)return dp[ind][s];
int same_pos=solve(ind,s-1,a)%mod;
int left=solve(ind-1,s-1,a)%mod;
int right=solve(ind+1,s-1,a)%mod;
return dp[ind][s]=(((same_pos+left)%mod)+right)%mod;
}
}
Optimised :
class Solution {
int mod=1000000007;
long dp[][];
public int numWays(int steps, int arrLen) {
//important
int len=Math.min(arrLen,steps);//as if steps less then arrlen then we do not
//move till last arrlen
dp=new long[len+1][steps+1];
for(int i=0;i<dp.length;i++){
Arrays.fill(dp[i],-1);
}
return solve(0,steps,len)%mod;
}
int solve(int ind,int s,int a){
if(ind<0 || ind>=a || s<0)return 0;
if(ind==0 && s==0)return 1;
if(s==0)return 0;
if(dp[ind][s]!=-1)return (int)dp[ind][s];
int same_pos=solve(ind,s-1,a)%mod;
int left=solve(ind-1,s-1,a)%mod;
int right=solve(ind+1,s-1,a)%mod;
dp[ind][s]=(((same_pos+left)%mod)+right)%mod;
return (int)dp[ind][s];
}
}