• Leetcode 650.只有两个键的键盘


    只有两个键的键盘

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

    1. Copy All (复制全部) : 你可以复制这个记事本中的所有字符(部分的复制是不允许的)。
    2. Paste (粘贴) : 你可以粘贴你上一次复制的字符。

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

    示例 1:

    输入: 3

    输出: 3

    解释:

    最初, 我们只有一个字符 'A'。

    第 1 步, 我们使用 Copy All 操作。

    第 2 步, 我们使用 Paste 操作来获得 'AA'。

    第 3 步, 我们使用 Paste 操作来获得 'AAA'。

    说明:

    1. n 的取值范围是 [1, 1000] 。

    思路

    Intuition

    We can break our moves into groups of (copy, paste, ..., paste). Let C denote copying and P denote pasting. Then for example, in the sequence of moves CPPCPPPPCP, the groups would be [CPP][CPPPP][CP].

    Say these groups have lengths g_1, g_2, .... After parsing the first group, there are g_1 'A's. After parsing the second group, there are g_1 * g_2 'A's, and so on. At the end, there are g_1 * g_2 * ... * g_n 'A's.

    We want exactly N = g_1 * g_2 * ... * g_n. If any of the g_i are composite, say g_i = p * q, then we can split this group into two groups (the first of which has one copy followed by p-1 pastes, while the second group having one copy and q-1 pastes).

    Such a split never uses more moves: we use p+q moves when splitting, and pq moves previously. As p+q <= pq is equivalent to 1 <= (p-1)(q-1), which is true as long as p >= 2 and q >= 2.

    Algorithm By the above argument, we can suppose g_1, g_2, ... is the prime factorization of N, and the answer is therefore the sum of these prime factors.

     1 class Solution {
     2     public int minSteps(int n) {
     3         int ans = 0, d = 2;
     4         while (n > 1) {
     5             while (n % d == 0) {
     6                 ans += d;
     7                 n /= d;
     8             }
     9             d++;
    10         }
    11         return ans;
    12     }
    13 }

  • 相关阅读:
    vs2017发布成功但是发布目录没有文件
    解决 CS0006 未能找到元数据文件
    EFPowertools 参数错误
    给WebAPI项目加上一个说明文档以及一个测试按钮
    Visual Studio 不显示SVN 状态图标解决方法
    JQuery PowerTimer 插件详解
    UML的各种关系理解
    C语言之如何上机运行第一个Hello World小程序
    打破 Serverless 落地边界,阿里云 SAE 发布 5 大新特性
    TCP/IP协议栈在Linux中内核中的运行时序分析
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10383081.html
Copyright © 2020-2023  润新知