[LeetCode] 650. 2 Keys Keyboard
来源:互联网 发布:audition mac 破解版 编辑:程序博客网 时间:2024/05/18 00:40
Problem:
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'.
题意分析:题目要求我们求得获得 n 个字符'A'(不能少也不能多)的最小操作步数,操作只有两种选择:
当前字符全部复制(Copy All)和粘(Paste)
解题思路:
为了找出规律,一般可以手动推算前面几项的结果:
n = 1时,结果显然为0,不用复制也不需要粘贴;
n = 2时,复制一遍,粘贴一遍,记为 cp,f(2) = 2;
n = 3时,复制一遍,粘贴两遍,记为 cpp,f(3) = 3;
n = 4时,复制一遍,粘贴三遍,记为cppp;另外一种选择为cpcp,f(4) = 4;
n = 5时,cpppp, f(5) = 5;
n = 6时,cpcpp,f(6) = f(2) + 3(6 / 2) = f(3) + 2(6 / 3)= 5;
n = 7时,cpppppp,f(7) = 7;
n = 8时,cpcppp或cpcpcp,f(8) = f(2) + 4(8 / 2) = f(4) + 2(8 / 4) = 6;
n = 9时,cppcpp,f(9) = f(3) + 3(9 / 3)= 6;
n = 10时,cppppcp或cpcpppp,f(10) = f(2) + 5(10 / 2)= f(5) + 2(10 / 5)= 7;
...
总结规律: f(n) = f(i) + n / i ,其中i为能整除n的整数,若n为素数,很容易理解,结果为其本身。
Solution:
class Solution {public: int minSteps(int n) { if (n == 1) return 0; vector<int> steps(n+1, 0); for (int i = 2; i <= n; i++) steps[i] = i; for (int i = 2; i <= n; i++) { for (int j = i / 2; j > 1; j--) { if (i % j == 0) { steps[i] = steps[j] + i / j; break; } } } return steps[n]; }};
- 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
- [LeetCode] 650. 2 Keys Keyboard
- Leetcode: 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- LeetCode-2 Keys Keyboard
- LeetCode:2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard(dp)
- LeetCode 650. 2 Keys Keyboard--动态规划
- [LeetCode] 650. 2 Keys Keyboard ## 题目描述
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- Java单例模式
- 使用git把本地文件放到github上去
- 所想
- HTML-1-基础练习
- 作业排程算法—动态规划实现
- [LeetCode] 650. 2 Keys Keyboard
- 八数码第四境界——暴力反向BFS+康托展开判重+打表+回溯记录路径
- 简书大V公然侮辱程序员群体低智商,低素质,恋尸癖!
- js和jquery中获取各种高度和宽度汇总
- Android中的Handler和AsyncTask的区别
- CoordinatorLayout 与ToolBar 和Fab实现滑动隐藏和显示的学习笔记
- 基于TCP的客户端、服务器端socket编程
- Python3 字典(dictionaries)
- Leetcode 283. Move Zeroes