650. 2 Keys Keyboard
来源:互联网 发布:web前端开发 薪资知乎 编辑:程序博客网 时间:2024/06/06 00:54
题目
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].
第一种方法可以模拟copy和paste操作,找到所有可能的操作个数,最后取最小值,这样的方法比较费时,另一种方法是根据n来决定操作个数,令f(n)表示构造长度为n所需的操作次数,如果n能被2整除,则f(n)=f(n/2)+2,即f(n/2)时copy并paste,类似n能被3整除时,f(n)=f(n/3)+3,则n能被i整除,f(n)=f(n/i)+i。
方法一:
class Solution {public: void steps(int n,int curlen,int copy,int cnt,int& minStep){ if(curlen+copy==n){//如果当前长度+copy==n,则只需要一次paste即可,故minStep与cnt+1取最小 minStep=min(minStep,cnt+1); return ; } else if(curlen+copy<n){//否则如果不到n,则有两种方案 steps(n,curlen+copy,copy,cnt+1,minStep);//第一是paste并且不copy,只增加一次操作 steps(n,curlen+copy,curlen+copy,cnt+2,minStep);//第二是paste并且copy,增加两次操作 } return ; } int minSteps(int n) { if(n==1){//如果n等于0,则无需复制粘贴直接返回 return 0; } int curlen=1;//当前长度初始化为1 int copy=1;//copy初始化为1 int minStep=INT_MAX;//保存最小的步骤个数 steps(n,curlen,copy,1,minStep); return minStep; }};方法二:
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; }};参考文章:[C++] Clean Code with Explanation - 4 lines, No DP
阅读全文
0 0
- 650. 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
- 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] 650. 2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard(dp)
- LeetCode 650. 2 Keys Keyboard--动态规划
- 各种算法OID
- strpos、 strstr、 substr三个函数的对比讲解
- windows调试 -- 创建.dump文件
- qduoj 生化危机&&ycb老师的电脑中毒了(邻接表)
- Hdu2544-最短路-【最短路】
- 650. 2 Keys Keyboard
- C++ Templates的多型威力(7)---《C++ Templates》
- Arduino学习日记一
- echarts x轴坐标文字显示不全
- Ubuntu 控制台ROS 使用table自动补全时 .gvfs Warning
- Windows上搭建Kafka运行环境
- 通过深度优先搜索(DFS)对图的边进行分类
- 在laravel5.4中使用Auth系统,配置邮箱
- 复杂类型的属性注入