title: Leetcode #377 Dynamic Programming Logic Question
body: <p>I have been struggling to comprehend one of the discussion solutions shown from <a href="https://leetcode.com/problems/combination-sum-iv/" rel="nofollow noreferrer">LC #377</a>. I'm not grasping how result is being incremented. I can see that there is the line:</p>
  <blockquote>
  <p>result += combinations(nums, dp, target - nums[i])</p>
  </blockquote>
  <p>which obviously is incrementing result, but <em>how exactly is result being incremented?</em> All I can see that is result is initialized to 0 then the line is executed if that if condition is satisfied, so wouldn't the line:</p>
  <blockquote>
  <p>dp[target] = result</p>
  </blockquote>
  <p>always be set to 0?. Really struggling comprehending, so would appreciate any help.</p>
  <p>Code:</p>
  <pre><code>class Solution {
  public int combinationSum4(int[] nums, int target) {
      int[] dp = new int[target + 1];
      Arrays.fill(dp, -1);
      dp[0] = 1;
      return combinations(nums, dp, target);
  }
  
  public int combinations(int[] nums, int[] dp, int target) {
      if (dp[target] != -1) {
          return dp[target];
      }
      int result = 0;
      for (int i = 0; i &lt; nums.length; i++) {
          if (target &gt;= nums[i]) {
              result += combinations(nums, dp, target - nums[i]);
          }
      }
      dp[target] = result;
      return result;
  }
  </code></pre>
  <p>}</p>