2 Keys Keyboard "programming question", keyskeyboard
Description
Solutions
I don't have to mention the question. As for the solution, I want to think about the dynamic planning of the past, but I think about it and it will be biased by a cute ting. But in the end, I still have a different path, this question is solved by studying the numbers themselves. The general idea is as follows:
For n characters A, if you want to find the minimum number of copy and paste steps, why not start from its factor? Taking 42 as an example, 42 = 21*2 = 7*3*2. That is to say, I need to copy the initial A, paste it into A, and then copy the two, paste 6 A records twice, copy these 6 A records, and paste them six times to get 42 A records. Of course, I cannot prove this theory for the time being, however, Accept confirms that this idea is OK.
C ++ code implementation
class Solution {public: int minSteps(int n) { int t = 2; int a[1000], p = -1;; while (n != 1) { while (n % t != 0) { t++; } a[++p] = t; n = n / t; } int result = 0; for (int i = 0; i <= p; ++i) { result += a[i]; } return result; }};
Running result display
Later, I checked the problem analysis and re-conceived the dynamic planning method, and found that the difference is similar. That is, dp [I] indicates the number of steps required to generate I characters, initial Value dp [0] = dp [1] = 0; state transition equation dp [I] = min (dp [I], dp [j] + I/j ), i> 1, j
class Solution {public: int minSteps(int n) { vector
dp(n+1,1000000); dp[0] = dp[1] = 0; for(int i=2;i