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: 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’.
Note:
The n will be in the range [1, 1000].
一开始只有一个字母A,现在要用copy,paste的操作得到n个A。
每次只能copy全部,或者paste,问至少要做多少次操作能得到n个A。
思路:
(1) DP
dp[i]表示得到 i 个A需要操作多少次
显然i = 0和i = 1时不需要操作, dp[0] = dp[1] = 0
i = 2: copy一次,paste一次,dp[2] = 2
i = 3: copy一次,paste 2次,dp[3] = 3
i = 4: 从AA copy一次,paste一次,即dp[4] = dp[2] + 2 = dp[2] + 4/2
i = 5: 从A copy一次,paste 4次,dp[5] = 5
i = 6: 从AAA copy一次,paste一次,即dp[6] = dp[3] + 2 = dp[3] + 6/3
得到n个A操作的上限就是n次,然后在n和上面dp中选较小的
至于dp中选被除的因子,就只能从大到小遍历了
//26ms
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-2; j > 1; j --) {
if(i % j == 0) {
int tmp = i / j;
dp[i] = Math.min(dp[i], dp[j] + tmp);
break;
}
}
}
return dp[n];
}
(2)递归
上面的DP做了很多不必要的计算,因为只想知道dp[n],但是dp[2]~dp[n]中用不到的部分也被计算了。
如果只想计算和dp[n]相关的部分,那就需要哪个就计算哪个,不需要的不计算
由dp[n]倒着往前计算,需要的部分递归再计算
这里递归的部分就相当于上面的dp[ j ]
//0ms
public int minSteps(int n) {
if(n <= 1) {
return 0;
}
if(n <= 3) {
return n;
}
int result = n;
for(int i = n-2; i >= 2; i--) {
if(n % i == 0) {
result = Math.min(result, minSteps(i) + n/i);
}
}
return result;
}