C++ iterative solution


  • 0
    J
    class Solution {
    public:
        vector<string> findStrobogrammatic(int n) {
            //result is the final result; result 2 is n-2(if n%2=0) or n-1 if n%2=1)
            if(n<=0) return {};
            
            vector<string> base1 = {"0", "1", "8"};
            vector<string> base2 = {"11", "69", "88", "96"};
            vector<string> base22 = {"00", "11", "69", "88", "96"};
            vector<string> result;
            vector<string> result2;
            
            for(int i =1;i<=n;i++){
                if (i==1)           {result = base1;}
                if (i==2)           {result = base2; result2 = base2;}
                if (i!=1 && i%2==1) {result = helper(result2, base1);}
                if (i!=2 && i%2==0) {
                    result = helper(result2, base22); 
                    result2 = result;
                } 
            }
            return result;
        }
        
        vector<string> helper(vector<string> input, vector<string> base ){
            vector<string> result;
            int n = input.size();
            for(int i = 0; i<n; i++){
                string cur = input[i];
                int size=cur.size();
                for(int j =0;j<base.size(); j++ ){
                    string temp = cur.insert(size/2, base[j]);
                    result.push_back(temp);
                    cur = input[i];//recover
                }
            }
            return result;
        }
    };

Log in to reply
 

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