LeetCode650. 2 Keys Keyboard
来源:互联网 发布:网球王子u17漫画软件 编辑:程序博客网 时间:2024/05/29 16:38
原题:https://leetcode.com/problems/2-keys-keyboard/discuss/
题目:
Initially on a notepad only one character ‘A’ is present. You can perform two operations on this notepad for each step:
Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
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:
The n will be in the range [1, 1000].
题解:
题中给出了两种操作:
1.复制当前的字符串;
2.将复制的字符串添加到原字符串后。
可以采用递归的方法。当目标字符串长度和当前字符串长度相等时,不需要任何操作,返回0,作为递归的终止条件。
当 n%2 = 0时, minStep(n) = minStep(n/2) + 2;
当 n%3 = 0时, minStep(n) = minStep(n/3) + 3;
当 n%5 = 0时, minStep(n) = minStep(n/5) + 5;
…….
事实上当n%k = 0且k为质数时, 想要从k变换到n,必须需要k步,即copy n/k,并paste k-1次。
而当n%k = 0且k为不为质数时时,假设k可以分解为m * n ;
如果将n直接分成k份,则需要m * n+minStep(n/k)步;
如果每次都除以较小因数因式分解,则需要m+n+minStep(n/k)步。
所以选择步数较少的第二种情况。
class Solution {public: int minSteps(int n) { if (n == 1) return 0; for (int i = 2; i < n; i++) { if (n % i == 0) { return i + minSteps(n/i); } } return n; }};
126 / 126 test cases passed.
Status: Accepted
Runtime: 3 ms
- LeetCode650. 2 Keys Keyboard
- LeetCode650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- LeetCode-2 Keys Keyboard
- LeetCode:2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650 2 Keys Keyboard
- LeetCode 650 2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard
- LeetCode -- 650. 2 Keys Keyboard
- Leetcode 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- Cloud中Hystrix仪表盘与Turbine集群监控
- 论文笔记-Synthetic Data for Text Localisation in Natural Images
- 线段树模板(区间和+区间最大值 + LAZY标记)
- 如何使用MySQL索引?
- Web开发者易犯的五大严重错误
- LeetCode650. 2 Keys Keyboard
- 怎么批量的将CAD文件转为pdf格式?
- 2017首届全球金融科技与区块链中国峰会—聆听行业领袖的真知灼见
- 当技术为组织所累时怎么办?将你的组织架构旋转90度!
- python 实现线性链表(单链表)--增加合并链表算法
- R与字符串操作
- Address localhost: 1099 is already in use问题解决
- KMP算法(java)
- OpenCV for Android 设置预览界面尺寸