Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4daabdd

Browse files
Create MinStepsto1
1 parent 84ee81f commit 4daabdd

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

‎Dynamic Programming/MinStepsto1

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include<iostream>
2+
#include<climits>
3+
using namespace std;
4+
int Minsteps_3(int n){
5+
int *ans=new int[n+1];
6+
ans[0]=0;
7+
ans[1]=0;
8+
for(int i=2;i<=n;i++){
9+
int a=INT_MAX,b=INT_MAX,c=INT_MAX;
10+
a=ans[i-1]+1;
11+
if(i%2==0){
12+
b=ans[i/2]+1;
13+
}
14+
if(i%3==0){
15+
c=ans[i/3]+1;
16+
}
17+
ans[i]=min(a,min(b,c));
18+
}
19+
return ans[n];
20+
}
21+
int Minsteps_helper(int n,int *ans){
22+
if(n<=1){
23+
return 0;
24+
}
25+
if(ans[n]!=-1){
26+
return ans[n];
27+
}
28+
int x=Minsteps_helper(n-1,ans);
29+
int y=INT_MAX,z=INT_MAX;
30+
if(n%2==0){
31+
y=Minsteps_helper(n/2,ans);
32+
}
33+
if(n%3==0){
34+
z=Minsteps_helper(n/3,ans);
35+
}
36+
int output=min(x,min(y,z))+1;
37+
ans[n]=output;
38+
return ans[n];
39+
}
40+
int Minsteps_2(int n){
41+
int *ans=new int[n+1];
42+
for(int i=0;i<=n;i++){
43+
ans[i]=-1;
44+
}
45+
return Minsteps_helper(n,ans);
46+
}
47+
int Minsteps(int n){
48+
if(n<=1){
49+
return 0;
50+
}
51+
int x=Minsteps(n-1);
52+
int y=INT_MAX,z=INT_MAX;
53+
if(n%2==0){
54+
y=Minsteps(n/2);
55+
}
56+
if(n%3==0){
57+
z=Minsteps(n/3);
58+
}
59+
return min(x,min(y,z))+1;
60+
}
61+
int main(){
62+
int n;
63+
cout<<"Enter the Number: "<<endl;
64+
cin>>n;
65+
cout<<Minsteps_3(n)<<endl;
66+
return 0;
67+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /