zoukankan      html  css  js  c++  java
  • [LeetCode] 650. 2 Keys Keyboard

    There is only one character 'A' on the screen of a notepad. You can perform two operations on this notepad for each step:

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

    Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.

    Example 1:

    Input: n = 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'.
    

    Example 2:

    Input: n = 1
    Output: 0

    Constraints:

    • 1 <= n <= 1000

    只有两个键的键盘。

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

    Copy All(复制全部):复制这个记事本中的所有字符(不允许仅复制部分字符)。
    Paste(粘贴):粘贴 上一次 复制的字符。
    给你一个数字 n ,你需要使用最少的操作次数,在记事本上输出 恰好 n 个 'A' 。返回能够打印出 n 个 'A' 的最少操作次数。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/2-keys-keyboard
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题的思路是动态规划。注意题意,一开始已经给定了一个A。为了最后得到 N 个 A,我们其实是有多种办法的,我参考了这个帖子。最直接的办法就是 copy 一次,然后 paste N - 1 次。但是这个方法是可以被优化的。举个例子,当 N = 4 的时候,这里有两种做法,一种是需要 copy 一次 A,paste 三次得到 AAAA;另一种是需要 copy 一次 A,paste 一次得到 AA,再 copy 一次(AA),再 paste 一次得到 AAAA。这里面其实是有规律可循的。规律的细节可以直接参见我参考的帖子,但是我这里一句话总结:如果 N 可以被之前某一个比 N 小的数字整除,那么为了最后得到 N 个字母 A,是有可能只需要更少的操作次数的。

    时间O(n^2)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int minSteps(int n) {
     3         int[] dp = new int[n + 1];
     4         for (int i = 2; i <= n; i++) {
     5             dp[i] = i;
     6             for (int j = i - 1; j > 1; j--) {
     7                 dp[i] = Math.min(dp[i], dp[j] + i / j);
     8             }
     9         }
    10         return dp[n];
    11     }
    12 }

    LeetCode 题目总结

  • 相关阅读:
    简单字符串处理应避免使用正则表达式
    提高正则表达式的可读性
    用零宽度断言匹配字符串中的特定位置
    避免不必要的回溯
    预编译正则表达式
    用Text::CSV_XS模块处理csv文件
    Ack 类似grep一样的查找
    Apache压力测试
    仅编译正则表达式一次
    排序上下箭头的是实现
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15316568.html
Copyright © 2011-2022 走看看