博客
关于我
650. 2 Keys Keyboard
阅读量:425 次
发布时间:2019-03-06

本文共 2081 字,大约阅读时间需要 6 分钟。

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: 3Output: 3Explanation: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]

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

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

 

转载地址:http://lktuz.baihongyu.com/

你可能感兴趣的文章
Mac下安装jdk
查看>>
Mac下安装PEAR
查看>>
Mac下安装PIL库
查看>>
mac下安装配置nginx
查看>>
MAC下安装配置Tomcat
查看>>
Mac下忘记MySQL密码可以这样做!
查看>>
Mac下显示\隐藏所有文件
查看>>
Mac下查看已安装的jdk版本及其安装目录
查看>>
mac下编译openjdk8?so easy!
查看>>
mac下配置PrintAssembly
查看>>
Mac下配置多个SSH-Key (gitLab)
查看>>
mac下面有epoll?
查看>>
Mac中禁止Chrome浏览器更新
查看>>
Mac使用git拉取代码
查看>>
mac关闭占用某个端口的进程
查看>>
mac删除appstore账号和更新失败的问题
查看>>
Mac单机安装Hadoop
查看>>
mac地址随机变化的解决方法(安卓手机通用)不用ROOT
查看>>
MAC壁纸工具
查看>>
Mac备忘录内容突然全部消失恢复
查看>>