title: Combination Sum
body: <p>Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.</p>
  
  <p>The same repeated number may be chosen from C unlimited number of times.</p>
  
  <blockquote>
  <pre><code>All numbers (including target) will be positive integers.
  Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  The combinations themselves must be sorted in ascending order.
  CombinationA &gt; CombinationB iff (a1 &gt; b1) OR (a1 = b1 AND a2 &gt; b2) OR … (a1 = b1 AND a2 = b2 AND … ai = bi AND ai+1 &gt; bi+1)
  The solution set must not contain duplicate combinations.
  </code></pre>
  </blockquote>
  
  <p>Example,
  Given candidate set <code>2,3,6,7</code> and target <code>7</code>,
  A solution set is:</p>
  
  <p><code>[2, 2, 3]
   [7]</code></p>
  
  <p>The solution code is :</p>
  
  <pre><code>class Solution {
      public:
  
      void doWork(vector&lt;int&gt; &amp;candidates, int index, vector&lt;int&gt; &amp;current, int currentSum, int target, vector&lt;vector&lt;int&gt; &gt; &amp;ans) {
          if (currentSum &gt; target) {
              return;
          }
          if (currentSum == target) {
              ans.push_back(current);
              return;
          }
          for (int i = index; i &lt; candidates.size(); i++) {
              current.push_back(candidates[i]);
              currentSum += candidates[i];
  
              doWork(candidates, i, current, currentSum, target, ans);
  
              current.pop_back();
              currentSum -= candidates[i];
          }
  
      }
  
      vector&lt;vector&lt;int&gt;&gt; combinationSum(vector&lt;int&gt; &amp;candidates, int target) {
          vector&lt;int&gt; current; 
          vector&lt;vector&lt;int&gt; &gt; ans;
          sort(candidates.begin(), candidates.end());
          vector&lt;int&gt; uniqueCandidates;
          for (int i = 0; i &lt; candidates.size(); i++) {
              if (i == 0 || candidates[i] != candidates[i-1]) {
                  uniqueCandidates.push_back(candidates[i]);
              }
          }
          doWork(uniqueCandidates, 0, current, 0, target, ans); 
          return ans;
      }
  };
  </code></pre>
  
  <p>Now, while i can understand the solution by taking an example case, how can i myself come out with such a solution. The main work is going in this function :</p>
  
  <pre><code>    for (int i = index; i &lt; candidates.size(); i++) {
          current.push_back(candidates[i]);
          currentSum += candidates[i];
  
          doWork(candidates, i, current, currentSum, target, ans);
  
          current.pop_back();
          currentSum -= candidates[i];
      }
  </code></pre>
  
  <p>Please tell me how to comprehend the above code and how to think that solution. I can solve basic recursion problems but these look out of reach. Thanks for your time.</p>