Minimum Steps to One

后端 未结 4 1239
庸人自扰
庸人自扰 2021-01-01 23:12

Problem statement :

On a positive integer, you can perform any one of the following 3 steps.

  1. Subtract 1 from it. ( n = n - 1 )
  2. If its divis
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 23:58

    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];
    
        } 
    

提交回复
热议问题