topic:
Initially on a notepad only one character ' a ' is present. Can perform two operations on this notepad for each step:
Copy all:you can copy all of the characters present on the Notepad (partial copy are not allowed).
Paste:you can Paste the characters which are copied.
Given a number n. You are have to get exactly n ' A ' in 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 the Copy all operation.
In step 2, we use the Paste operation to get ' AA '.
In step 3, we use the Paste operation to get ' AAA '.
Note:
The n would be in the range [1, 1000].
idea:
This problem is a dynamic programming problem, the state transition equation is not very obvious, need careful analysis.
First the minimum of the DP is set to infinity (0X7FFFFFFF), the initialization condition is: dp[0]=dp[1]=0 dp[0] = dp[1] = 0, the state transition equation is:
Dp[i]=min (dp[i],dp[j]+i/j), i>1,j<i and I are integral times of j dp[i] = min (dp[i), dp[j]+i/j), I>1, J
The state transition equation above indicates that if I is a multiple of J, then I can be obtained by pasting (i/j-1) times J, plus a copy operation, then the dp[i can be obtained through dp[j]+i/j operation. C + + code is as follows:
Class Solution {public
:
int minsteps (int n) {
vector<int> dp (N+1,0X7FFFFFFF);
Dp[0] = dp[1] = 0;
for (int i=2;i<n+1;++i) {
for (int j=1;j<i;++j) {
if (i%j==0) {
Dp[i] = min (dp[i), dp[j]+i/j);
}
}
return dp[n];
}
;