Whey my method has "Time Limit Exceeded"

  • 0

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

    class Solution {
        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]});
            for (int i=index; i<words.size(); i++) {
                helper(res, temp, words, i+1, k-1);
        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.