Cpp code encountered Runtime Error but success in my local machine, WHY?


  • 0

    I use backtrack:

    class Solution {
    public:
    
        int minMutation(string start, string end, vector<string>& bank) {
            bool endInBank = false;
            for(vector<string>::iterator it = bank.begin(); it != bank.end(); it++) {
                endInBank |= end.compare(*it) == 0;
            }
            if(!endInBank) {
                return -1;
            }
    
            int n = bank.size();
            int* record = new int[n + 1];
            int minStep = n;
            int step = 0;
            tryMutate(start, end, bank, record, step, minStep);
            
            delete []record;
            return minStep;
        }
    
        void tryMutate(string start, string end, vector<string>& bank, int* rec, int step, int& minStep) {
            for(int i = 0; i < bank.size(); i++) {
                bool used = false;
                for(int s = 0; s < step; s++) {
                    if(rec[s] == i) {
                        used = true;
                        break;
                    }
                }
    
                if(used) {
                    continue;
                } else if(canMutate(start, bank[i])){
                         
                    if(bank[i].compare(end) == 0) {
                        step = step + 1;
                        if(step < minStep) {
                            minStep = step;
                        }
                        return;
                    }
    
                    rec[step + 1] = i;
                    tryMutate(bank[i], end, bank, rec, step + 1, minStep);
                }
            }
        }
    
        bool canMutate(string a, string b) {
            if(a.size() != b.size()) {
                return false;
            }
    
            int count = 0;
            int n = a.size();
            for(int i = 0; i < n; i++) {
    
                if(b[i] != 'A' && b[i] != 'G' && b[i] != 'C' && b[i] != 'T') {
                    return false;
                }
    
                if(a[i] != b[i]) {
                    if(count > 0) {
                        return false;
                    }
                    count++;
                }
            }
    
            return true;
        }
    
    };
    

    It met Runtime Error in bellowing test case:

    "AAAACCCC"
    "CCCCCCCC"
    ["AAAACCCA","AAACCCCA","AACCCCCA","AACCCCCC","ACCCCCCC","CCCCCCCC","AAACCCCC","AACCCCCC"]

    But I test in my local machine it output the answer(4) which is right...


Log in to reply
 

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