Note that there are some explanatory texts on larger screens.

plurals
  1. POComparison of running times - similar code runs 4 times slower
    primarykey
    data
    text
    <p>I am solving the palindrome partition problem which requires to return all palindrome partitions of a given string (<a href="http://oj.leetcode.com/problems/palindrome-partitioning/" rel="nofollow">http://oj.leetcode.com/problems/palindrome-partitioning/</a>). I found two solutions to this problem. I am having difficulty to understand why there is a huge difference in the running times of these two approaches:</p> <p>(Assume <code>bool isPal()</code> is a given function which tells whether given string is palindrome or not in O(length) time)</p> <p>1st Solution: (Uses backtracking):</p> <pre><code>void find(string s, int start, vector&lt;string&gt; &amp;r, vector&lt;vector&lt;string&gt; &gt; &amp;res){ if (start &gt;= s.size()){ res.push_back(r); }else{ for (int i=start;i&lt;s.size();i++){ if (isPal(s.substr(start, i-start+1))){ r.push_back(s.substr(start,i-start+1)); find(s,i+1,r,res); r.pop_back(); } } } } vector&lt;vector&lt;string&gt;&gt; partition(string s) { vector&lt;vector&lt;string&gt; &gt; res; vector&lt;string&gt; r; find(s,0,r,res); return res; } </code></pre> <p>2nd Solution:</p> <pre><code>vector&lt;vector&lt;string&gt; &gt; partition(string s) { vector&lt;vector&lt;string&gt; &gt; answer; if(s.size() == 0) return answer; // if s is Palindrome, push to answer if(isPal(s)) answer.push_back(vector&lt;string&gt;(1,s)); if(s.size() == 1) return answer; for(int i=1; i&lt;s.size(); ++i) { string s1 = s.substr(0, i); string s2 = s.substr(i, s.size()-i); if(isPal(s1)) { // get sub_answers of partition(s[i:]) vector&lt;vector&lt;string&gt; &gt; sub_answer = partition(s2); // add s1 to the begin of sub_answers for(int j=0; j&lt;sub_answer.size(); ++j) { sub_answer[j].insert(sub_answer[j].begin(), s1); answer.push_back(sub_answer[j]); } } } return answer; } </code></pre> <p>Even though both the solutions have the same underlying idea, the 1st solution runs in <strong>108ms</strong>, while the 2nd one takes <strong>472ms</strong> time. Is this because of theoretical inefficiency (maybe 2nd solution solves a single problem multiple times) or because of inefficient implementation (some C++ concepts)? Please point out the reason for inefficiency of 2nd solution.</p> <p><strong>Note</strong>: Both solutions are correct and give the same result.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload