650. 2 Keys Keyboard

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: 3
Output: 3
Explanation:
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的最小操作步骤的数目minStep
  1. Copy All: 只能全部复制,不能部分复制.
  2. Paste: 拷贝留在剪贴板上的字符
复制代码
 1     public int minSteps(int n) {
 2 //        先把dp的最小步骤都设置为无穷大, 初始化条件为:dp[0]=dp[1]=0 ,状态转移方程为:
 3 //        dp[i]=min(dp[i],dp[j]+i/j),i>1,j<i且i是j的整数倍
 4 //        上述状态转移方程表示:如果i是j的倍数,那么i可以通过粘贴(i/j-1)次j 得到, 再加上一次复制操作,
 5         int[] dp = new int[n+1];
 6         if (n<2) return 0;
 7         Arrays.fill(dp,Integer.MAX_VALUE);
 8         dp[0]=0;
 9         dp[1]=0;
10         for (int i=2;i<n+1;i++)
11         {
12             for (int j=1;j<i;j++)
13             {
14                 if (i%j==0) dp[i]=Math.min(dp[i],dp[j] + i/j);
15             }
16         }
17         return dp[n];        
18     }
复制代码

 

posted @   daniel456  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示