Friday, July 15, 2016

320. Generalized Abbreviation

I observed the rule is the abbreviation number doesn't appear consecutively. So in the backtracking solution, we need to have a flag in the API to indicate that whether the previous character is an abbreviation number or not. I made some mistakes in the place in red.

1:  class Solution {  
2:  public:  
3:    vector<string> generateAbbreviations(string word) {  
4:      vector<string> res;  
5:      helper(word, "", res, 0, false);  
6:      return res;  
7:    }  
8:    void helper(string &word, string abbr, vector<string> &res, int i, bool prev) {  
9:      if (i == word.size()) {  
10:        res.push_back(abbr);  
11:        return;  
12:      }  
13:      helper(word, abbr+word[i], res, i+1, false);  
14:      if (!prev) {  
15:        for (int j = 1; i+j <= word.size(); j++)  
16:          helper(word, abbr+to_string(j), res, i+j, true);  
17:      }  
18:    }  
19:  };  

No comments:

Post a Comment