-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04-Frog_Jump-With-K-Steps.cpp
54 lines (51 loc) · 1.15 KB
/
04-Frog_Jump-With-K-Steps.cpp
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
#include <bits/stdc++.h>
using namespace std;
// Tabulation
int solve1(int ind, vector<int> &height, int k, vector<int> &dp)
{
dp[0] = 0;
if (ind <= 0)
return 0;
for (int i = 1; i <= ind; i++)
{
int steps = INT_MAX;
for (int j = 1; j <= k; j++)
{
if ((i - j) >= 0)
{
int jump = dp[i - j] + abs(height[i] - height[i - j]);
steps = min(steps, jump);
}
}
dp[i] = steps;
}
return dp[ind];
}
// Memoization
int solve2(int ind, vector<int> &height, int k, vector<int> &dp)
{
if (ind == 0)
return 0;
if (dp[ind] != -1)
return dp[ind];
int steps = INT_MAX;
for (int j = 1; j <= k; j++)
{
if ((ind - j) >= 0)
{
int jump = solve2(ind - j, height, k, dp) + abs(height[ind] - height[ind - j]);
steps = min(steps, jump);
}
}
return dp[ind] = steps;
}
int main()
{
vector<int> height{10, 30, 40, 50, 20};
int n = height.size();
vector<int> dp(n, -1);
int k = 3;
int ans = solve2(n - 1, height, k, dp);
cout << ans;
return 0;
}