650. 2 Keys Keyboard

本文探讨了一种算法问题,即如何通过最少的操作步骤在记事本上生成指定数量的字符'A'。文中提供了两种解决方案,一种是递归模拟CopyAll与Paste操作,另一种则是采用数学方法,利用最大公约数进行优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. Paste: You can paste the characters which are copied last time.

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:

  1. The n will be in the range [1, 1000].
分析

第一种方法可以模拟copy和paste操作,找到所有可能的操作个数,最后取最小值,这样的方法比较费时,另一种方法是根据n来决定操作个数,令f(n)表示构造长度为n所需的操作次数,如果n能被2整除,则f(n)=f(n/2)+2,即f(n/2)时copy并paste,类似n能被3整除时,f(n)=f(n/3)+3,则n能被i整除,f(n)=f(n/i)+i。

方法一:

class Solution {
public:
    void steps(int n,int curlen,int copy,int cnt,int& minStep){
        if(curlen+copy==n){//如果当前长度+copy==n,则只需要一次paste即可,故minStep与cnt+1取最小
            minStep=min(minStep,cnt+1);
            return ;
        }
        else if(curlen+copy<n){//否则如果不到n,则有两种方案
            steps(n,curlen+copy,copy,cnt+1,minStep);//第一是paste并且不copy,只增加一次操作
            steps(n,curlen+copy,curlen+copy,cnt+2,minStep);//第二是paste并且copy,增加两次操作
        }
        return ;
    }
    int minSteps(int n) {
        if(n==1){//如果n等于0,则无需复制粘贴直接返回
            return 0;
        }
        int curlen=1;//当前长度初始化为1
        int copy=1;//copy初始化为1
        int minStep=INT_MAX;//保存最小的步骤个数
        steps(n,curlen,copy,1,minStep);
        return minStep;
    }
};
方法二:

class Solution {
public:
    int minSteps(int n) {
        if (n == 1) return 0;
        for (int i = 2; i < n; i++)
            if (n % i == 0) 
                return i + minSteps(n / i);
        return n;
    }
};
参考文章: [C++] Clean Code with Explanation - 4 lines, No DP


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值