📌  相关文章
📜  通过在每个步骤加1或加倍来最小化从0到K的步骤

📅  最后修改于: 2021-05-14 01:50:44             🧑  作者: Mango

给定正整数K ,任务是找到以下两种类型的最小操作数,将0更改为K所需:

  • 将一个加到操作数
  • 将操作数乘以2。

例子:

方法:

  • 如果K是一个奇数,则最后一步必须为其加1。
  • 如果K是偶数,则最后一步是乘以2以使步数最小化。
  • 创建一个dp []表,该表存储在每个dp [i]中,这是达到i所需的最小步骤。

下面是上述方法的实现:

C++
// C++ program to implement the above approach
#include 
using namespace std;
  
// Function to find minimum operations
int minOperation(int k)
{
    // vector dp is initialised
    // to store the steps
    vector dp(k + 1, 0);
  
    for (int i = 1; i <= k; i++) {
  
        dp[i] = dp[i - 1] + 1;
  
        // For all even numbers
        if (i % 2 == 0) {
            dp[i]
                = min(dp[i],
                      dp[i / 2] + 1);
        }
    }
    return dp[k];
}
  
// Driver Code
int main()
{
    int K = 12;
    cout << minOperation(k);
}


Java
// Java program to implement the above approach
class GFG{
      
// Function to find minimum operations
static int minOperation(int k)
{
      
    // dp is initialised
    // to store the steps
    int dp[] = new int[k + 1];
  
    for(int i = 1; i <= k; i++)
    {
       dp[i] = dp[i - 1] + 1;
         
       // For all even numbers
       if (i % 2 == 0)
       {
           dp[i] = Math.min(dp[i], dp[i / 2] + 1);
       }
    }
    return dp[k];
}
  
// Driver Code
public static void main (String []args)
{
    int K = 12;
    System.out.print( minOperation(K));
}
}
  
// This code is contributed by chitranayal


Python3
# Python3 program to implement the above approach
  
# Function to find minimum operations
def minOperation(k):
      
    # dp is initialised
    # to store the steps
    dp = [0] * (k + 1)
  
    for i in range(1, k + 1):
        dp[i] = dp[i - 1] + 1
  
        # For all even numbers
        if (i % 2 == 0):
            dp[i]= min(dp[i], dp[i // 2] + 1)
  
    return dp[k]
  
# Driver Code
if __name__ == '__main__':
      
    k = 12
      
    print(minOperation(k))
  
# This code is contributed by mohit kumar 29


C#
// C# program to implement the above approach
using System;
class GFG{
      
// Function to find minimum operations
static int minOperation(int k)
{
      
    // dp is initialised
    // to store the steps
    int []dp = new int[k + 1];
  
    for(int i = 1; i <= k; i++)
    {
        dp[i] = dp[i - 1] + 1;
              
        // For all even numbers
        if (i % 2 == 0)
        {
            dp[i] = Math.Min(dp[i], dp[i / 2] + 1);
        }
    }
    return dp[k];
}
  
// Driver Code
public static void Main()
{
    int K = 12;
    Console.Write(minOperation(K));
}
}
  
// This code is contributed by Nidhi_Biet


输出:
5