650. 2 Keys Keyboard

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

 

Approach #1: DP. [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int minSteps(int n) {
        int[] dp = new int[n+1];
         
        for (int i = 2; i <= n; ++i) {
            dp[i] = i;
            for (int j = i-1; j > 1; --j) {
                if (i % j == 0) {
                    dp[i] = dp[j] + (i/j);
                    break;
                }
            }
        }
         
        return dp[n];
    }
}

  

Approach #2: Greedy. [C++]

1
2
3
4
5
6
7
8
9
10
public int minSteps(int n) {
    int s = 0;
    for (int d = 2; d <= n; d++) {
        while (n % d == 0) {
            s += d;
            n /= d;
        }
    }
    return s;
}

  

Analysis:

We look for a divisor d so that we can make d copies of (n / d) to get n. The process of making d copies takes d steps (1 step of copy All and d-1 steps of Paste)

 

We keep reducing the problem to a smaller one in a loop. The best cases occur when n is decreasing fast, and method is almost O(log(n)). For example, when n = 1024 then n will be divided by 2 for only 10 iterations, which is much faster than O(n) DP method.

 

The worst cases occur when n is some multiple of large prime, e.g. n = 997 but such cases are rare.

 

 

Reference:

https://leetcode.com/problems/2-keys-keyboard/discuss/105897/Loop-best-case-log(n)-no-DP-no-extra-space-no-recursion-with-explanation

 

https://leetcode.com/problems/2-keys-keyboard/discuss/105899/Java-DP-Solution

 

posted @   Veritas_des_Liberty  阅读(228)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
历史上的今天:
2018-03-12 B - Factors of Factorial
点击右上角即可分享
微信分享提示