Whey my method has "Time Limit Exceeded"


  • 0
    L

    I used Backtracking, but it has Time Limit Exceeded error, can anybody tell me the reason?

    class Solution {
    public:
        bool isPalindrome(string s) {
            int l = 0, r = s.size()-1;
            while(l < r) {
                if (s[l++] != s[r--])
                    return false;
            }
            return true;
        }
        void helper(vector<vector<int>> &res, vector<int> &temp, vector<string> &words, int index, int k){
            if(0 == k){
                if(isPalindrome( words[ temp[0] ] + words[temp[1]]))    res.push_back({temp[0],temp[1]});
                if(isPalindrome( words[temp[1]] + words[temp[0]]))  res.push_back({temp[1],temp[0]});
                return;
            }
            for (int i=index; i<words.size(); i++) {
                temp.push_back(i);
                helper(res, temp, words, i+1, k-1);
                temp.pop_back();
            }
        }
        vector<vector<int>> palindromePairs(vector<string>& words) {
            vector<vector<int>>  ans;
            vector<int> temp;
            helper(ans, temp, words, 0, 2);
            return ans;
        }
    };
    

Log in to reply
 

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