-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStepTo1DP.cpp
More file actions
67 lines (57 loc) · 1.07 KB
/
MinStepTo1DP.cpp
File metadata and controls
67 lines (57 loc) · 1.07 KB
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
#include <iostream>
using namespace std;
int minStepsHelper(int n, int *ans) {
// Base case
if(n <= 1) {
return 0;
}
// Check if output already exists
if(ans[n] != -1) {
return ans[n];
}
// Calculate output
int x = minStepsHelper(n - 1, ans);
int y = INT_MAX, z = INT_MAX;
if(n % 2 == 0) {
y = minStepsHelper(n/2, ans);
}
if(n % 3 == 0) {
z = minStepsHelper(n/3, ans);
}
int output = min(x, min(y, z)) + 1;
// Save output for future use
ans[n] = output;
return output;
}
int minSteps(int n) {
int *ans = new int[n+1];
for(int i = 0; i <= n; i++) {
ans[i] = -1;
}
return minStepsHelper(n, ans);
}
int main() {
int n;
cin >> n;
cout << minSteps(n) << endl;
}
/* USING RECURSION ONLY
int minSteps(int n) {
// Base case
if(n <= 1) {
return 0;
}
// Recursive call
int x = minSteps(n - 1);
int y = INT_MAX, z = INT_MAX;
if(n % 2 == 0) {
y = minSteps(n/2);
}
if(n % 3 == 0) {
z = minSteps(n/3);
}
// Calculate final output
int ans = min(x, min(y, z)) + 1;
return ans;
}
*/