c++ backtracking solution


  • 0
    J

    use a int flag to decide whether to for number or string. 0 means both are ok at the beginning, 1 and 2 are for either number or for string.

    class Solution {
    public:
        void backTracking(string word,vector<string> &rst,string temp,int pos,int flag){
            if(pos==word.size())rst.push_back(temp);
            for(int i=pos;i<word.size();i++){
                if(flag==0||flag==1)backTracking(word,rst,temp+to_string(i-pos+1),i+1,2);
                if(flag==0||flag==2)backTracking(word,rst,temp+word.substr(pos,i-pos+1),i+1,1);
            }
        }
        vector<string> generateAbbreviations(string word) {
            vector<string> rst;
            string temp;
            backTracking(word,rst,temp,0,0);
            return rst;
        }
    };
    

Log in to reply
 

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