[LeetCode] 650. 2 Keys Keyboard

42 篇文章 0 订阅
37 篇文章 0 订阅

题目链接: https://leetcode.com/problems/2-keys-keyboard/description/

Description

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].

解题思路

题意大致为,从初始状态长度为 1 的串开始,使用最少的步数(复制或粘贴),来获取长度为 n 的串。其中,复制和粘贴各算一步

首先,可以肯定复制、粘贴越长的串,使用的总步数越少。比如要获取一个长度为 6 的串 AAAAAA,复制粘贴 5 个长度为 1 的串 A,共需要 6 步(复制 1 次,粘贴 5 次);而先复制粘贴长度为 1 的串形成一个长度为 2 的串 AA,再复制这个长度为 2 的串,粘贴 2 次,就可以用 5 步(复制 2 次, 粘贴 3 次)来获取目标串。

另外,能分应该尽量分。例如要获取长度为 12 的串,有多种获取方法,其中一种是直接复制 A 粘贴 5 次获取长度为 6 的串 AAAAAA,然后再复制粘贴这个串获取目标串,共需 8 步;另一种是,先复制粘贴 A 各 1 次,获取长度为 2 的串 AA,在复制 AA,粘贴 2 次,获取长度为 6 的串 AAAAAA,然后在复制粘贴各 1 次获取目标串,共需 7 步,比之前少了 1 步。

用式子来表示。设要获取长度为 n 的串所需最少步数为 f(n)。从一个大的数 n 开始考虑,

  • 若其能被 2 整除,即 n % 2 == 0 ,则 f(n) = 2 + f(n / 2),其中的 2 为复制 1 次和粘贴 1 次长度为 n / 2 的串所用的步数。
  • 若其能被 3 整除,即 n % 3 == 0,则 f(n) = 3 + f(n / 3),其中 3 为复制 1 次和粘贴 2 次长度为 n / 3 的串所用的步数。

从上述可知,这道题就转变为对 n 进行质因数分解,将所有的质因数相加即为解。

Code

class Solution {
public:
    int minSteps(int n) {
        int res = 0, tmp = n;
        for (int i = 2; i <= n && tmp != 1; ++i) {
            while (tmp % i == 0) {
                res += i;
                tmp /= i;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值