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:
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 exactlyn
‘A’ on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to getn
‘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'.
题目大意:给定一个笔记本,当前含有一个字符A,可以做复制与粘贴操作,求给定一个数字n,需要执行多少步操作,使字符数达到n个。
思路:dp dp[i]=min(dp[i],dp[i]+i/j) i是j的整数倍,如果i是j的整数倍,则i可以通过粘贴i/j-1次得到j,再加上一次复制,为i/j,dp[j]表示当n等于j时最小的步骤,所以可以通过dp[j]+i/j得到dp[i]。
代码
package DP; /** * @Author OovEver * @Date 2017/12/15 10:18 */ public class LeetCode650 { 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]; } }