博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
650. 2 Keys Keyboard
阅读量:5163 次
发布时间:2019-06-13

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

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

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10517029.html

你可能感兴趣的文章
IP V4 和 IP V6 初识
查看>>
Spring Mvc模式下Jquery Ajax 与后台交互操作
查看>>
(转)matlab练习程序(HOG方向梯度直方图)
查看>>
『Raid 平面最近点对』
查看>>
【ADO.NET基础-数据加密】第一篇(加密解密篇)
查看>>
C语言基础小结(一)
查看>>
STL中的优先级队列priority_queue
查看>>
UE4 使用UGM制作血条
查看>>
浏览器对属性兼容性支持力度查询网址
查看>>
OO学习总结与体会
查看>>
虚拟机长时间不关造成的问题
查看>>
面试整理:Python基础
查看>>
Python核心编程——多线程threading和队列
查看>>
Program exited with code **** 相关解释
查看>>
植物大战僵尸中文年度版
查看>>
26、linux 几个C函数,nanosleep,lstat,unlink
查看>>
投标项目的脚本练习2
查看>>
201521123107 《Java程序设计》第9周学习总结
查看>>
Caroline--chochukmo
查看>>
iOS之文本属性Attributes的使用
查看>>