Leetcode--650. 2 Keys Keyboard

Source: Internet
Author: User
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];
    }
;

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.