LeetCode650. 2 Keys Keyboard

本文介绍了一个LeetCode上的问题,即如何使用最少的操作步骤在记事本上得到n个字符'A'。提供了两种操作:复制全部和粘贴,并给出了一种递归解决方案。

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

原题:https://leetcode.com/problems/2-keys-keyboard/discuss/


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

Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
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:
The n will be in the range [1, 1000].


题解:
题中给出了两种操作:
1.复制当前的字符串;
2.将复制的字符串添加到原字符串后。
可以采用递归的方法。当目标字符串长度和当前字符串长度相等时,不需要任何操作,返回0,作为递归的终止条件。

当 n%2 = 0时, minStep(n) = minStep(n/2) + 2;
当 n%3 = 0时, minStep(n) = minStep(n/3) + 3;
当 n%5 = 0时, minStep(n) = minStep(n/5) + 5;
…….

事实上当n%k = 0且k为质数时, 想要从k变换到n,必须需要k步,即copy n/k,并paste k-1次。
而当n%k = 0且k为不为质数时时,假设k可以分解为m * n ;
如果将n直接分成k份,则需要m * n+minStep(n/k)步;
如果每次都除以较小因数因式分解,则需要m+n+minStep(n/k)步。
所以选择步数较少的第二种情况。


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

126 / 126 test cases passed.
Status: Accepted
Runtime: 3 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值