Problem statement :
On a positive integer, you can perform any one of the following 3 steps.
Recursive Solution For this problem
public static int countMinStepsTo1(int n){
if(n==1)
{
return 0;
}
int count1,count2=Integer.MAX_VALUE,count3=Integer.MAX_VALUE;
count1 = countMinStepsTo1(n-1);
if((n%2)==0)
{
count2=countMinStepsTo1(n/2);
}
if((n%3)==0)
{
count3=countMinStepsTo1(n/3);
}
return 1+Math.min(count1,Math.min(count2,count3));
}
DP Approch For this problem
public static int countstepsDP(int n)
{
int storage[] = new int[n+1];
storage[1]=0;
for(int i=2; i<=n;i++)
{
int min=storage[i-1];
if(i%3==0)
{
if(min>storage[i/3])
{
min=storage[i/3];
}
}
if(i%2==0)
{
if(min>storage[i/2])
{
min=storage[i/2];
}
}
storage[i]=1+min;
}
return storage[n];
}