14-line c++ simple dfs


  • 0
    W
    class Solution {
    public:
    
        void dfs(const string& w, int pos, string prev, bool prevNum, vector<string>& ans) {
            if (pos==w.length())
                ans.push_back(prev);
            else
                for (int i=0; i <= (int)w.length()-pos; i++) {
                    if (i==0)
                        dfs(w, pos+1, prev+w[pos], false, ans);
                    else  if (prevNum==false)
                        dfs(w, pos+i, prev+to_string(i), true, ans);
                    else
                        break;
                }
        }
        
        vector<string> generateAbbreviations(string word) {
            vector<string> ans;
            if (word!="")
                dfs(word, 0, "", false, ans);
            else
                ans.push_back("");
            
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.