LeetCode 题解工作台

两个键的键盘

最初记事本上只有一个字符 'A' 。你每次可以对这个记事本进行两种操作: Copy All (复制全部):复制这个记事本中的所有字符(不允许仅复制部分字符)。 Paste (粘贴):粘贴 上一次 复制的字符。 给你一个数字 n ,你需要使用最少的操作次数,在记事本上输出 恰好 n 个 'A' 。返回…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

定义 为输出 个字符的最少操作次数。初始化 `dfs(1)=0`。 当 $i\gt 1$ 时,有:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

最初记事本上只有一个字符 'A' 。你每次可以对这个记事本进行两种操作:

  • Copy All(复制全部):复制这个记事本中的所有字符(不允许仅复制部分字符)。
  • Paste(粘贴):粘贴 上一次 复制的字符。

给你一个数字 n ,你需要使用最少的操作次数,在记事本上输出 恰好 n 个 'A' 。返回能够打印出 n 个 'A' 的最少操作次数。

 

示例 1:

输入:3
输出:3
解释:
最初, 只有一个字符 'A'。
第 1 步, 使用 Copy All 操作。
第 2 步, 使用 Paste 操作来获得 'AA'。
第 3 步, 使用 Paste 操作来获得 'AAA'。

示例 2:

输入:n = 1
输出:0

 

提示:

  • 1 <= n <= 1000
lightbulb

解题思路

方法一:记忆化搜索

定义 dfs(i)dfs(i) 为输出 ii 个字符的最少操作次数。初始化 dfs(1)=0

i>1i\gt 1 时,有:

dfs(i)=minji(dfs(ij)+j,i),2j<idfs(i)=\min _{j \mid i} (dfs(\frac{i}{j})+j, i), 2\leq j\lt i

时间复杂度 O(nn)O(n\sqrt{n})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def minSteps(self, n: int) -> int:
        @cache
        def dfs(n):
            if n == 1:
                return 0
            i, ans = 2, n
            while i * i <= n:
                if n % i == 0:
                    ans = min(ans, dfs(n // i) + i)
                i += 1
            return ans

        return dfs(n)
speed

复杂度分析

指标
时间O(\sqrt{n})
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates a strong understanding of dynamic programming and optimization techniques.

  • question_mark

    Candidate applies mathematical insights, considering divisors and states, to minimize operations.

  • question_mark

    Candidate is able to explain how state transition and factorization techniques work together.

warning

常见陷阱

外企场景
  • error

    Not considering the factorization of n and how it affects the number of operations.

  • error

    Overcomplicating the problem with unnecessary calculations or inefficient approaches.

  • error

    Failing to optimize for time complexity when implementing dynamic programming solutions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider variations where other operations besides 'Copy All' and 'Paste' are allowed.

  • arrow_right_alt

    Extend the problem to handle cases with multiple characters initially on the screen.

  • arrow_right_alt

    Implement a solution for a larger range of n values, focusing on efficiency for large inputs.

help

常见问题

外企场景

两个键的键盘题解:状态·转移·动态规划 | LeetCode #650 中等