2 Keys Keyboard "programming question", keyskeyboard

Source: Internet
Author: User

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
             
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.