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

📅  最后修改于: 2021-09-08 12:40:46             🧑  作者: 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


Javascript


输出:
5