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 题目总结

  • 相关阅读:
    getBoundingClientRect()方法
    Sublime Text3 安装less
    less知识点总结(一)
    跨域知识(二)——JSONP
    面向过程和面向对象的区别(转)
    暴力+DP:买卖股票的最佳时机
    车的可用捕获量(3.26leetcode每日打卡)
    三维形体的表面积(3.25leetcode每日打卡)
    基础练习:FJ的字符串
    DP:打家劫舍
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15316568.html
Copyright © 2011-2022 走看看