<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p>

<ul>
	<li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li>
	<li>Paste: You can paste the characters which are copied last time.</li>
</ul>

<p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> Initially, we have one character &#39;A&#39;.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get &#39;AA&#39;.
In step 3, we use Paste operation to get &#39;AAA&#39;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 1000</code></li>
</ul>

class Solution {
public:
    int minSteps(int n) {

        int** memo = new int*[n];
        for(int i = 0; i < n; ++i) {
            memo[i] = new int[n];
            for(int j = 0; j < n; ++j) {
                memo[i][j] = -1;
            }
        } 

        return find(1, 0, n, memo);
    }

    //s: how many on screen, r: how many on copy paste register
    int find(int s, int r, int n, int** memo) {

        if(s == n) return 0;
        if(s > n) return 1000;

        if(memo[s][r] != -1) {
            return memo[s][r];
        }

        //need to copy something
        if(r == 0) memo[s][r] = 1 + find(s, s, n, memo);
        //shouldn't copy again
        else if(s == r) memo[s][r] = 1 + find(s + r, r, n, memo);
        //have a choice between copy and paste
        else memo[s][r] = 1 + min(find(s + r, r, n, memo), find(s, s, n, memo));

        return memo[s][r];
    }
};
128118