650. 2 Keys Keyboard

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: 

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. Paste: You can paste the characters which are copied last time.

 

Given a number n. You have to get exactly n 'A' on 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 Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
class Solution {
public:
    enum Action { COPYALL, PASTE };
    int minSteps(int n) {
        if(n==1) return 0;
        int step = 1;
        int min_step = INT_MAX;
        dfs(1,n,step,min_step,COPYALL,1);
        return min_step;
    }
    
    void dfs(int curr,int n,int step,int &min_step,Action action,int last_copy)
    {
        if(curr>n) return;
        if(curr==n)
        {
            min_step = min(step,min_step); 
            return;
        }
        if(action == COPYALL)
            dfs(curr+last_copy,n,step+1,min_step,PASTE,last_copy);//paste
        else
        {
            dfs(curr,n,step+1,min_step,COPYALL,curr);//COPY
            dfs(curr+last_copy,n,step+1,min_step,PASTE,last_copy);//paste
        }    
    }
};

 

posted @ 2017-12-14 08:43  jxr041100  阅读(118)  评论(0编辑  收藏  举报