{"id":27160,"date":"2018-01-03T21:55:05","date_gmt":"2018-01-03T16:25:05","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27160"},"modified":"2018-01-03T21:55:05","modified_gmt":"2018-01-03T16:25:05","slug":"java-programming-subset-sum-problem","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-subset-sum-problem\/","title":{"rendered":"Java Programming &#8211; Subset Sum Problem"},"content":{"rendered":"<p>Given a set of non-negative integers, and a value <em>sum<\/em>, determine if there is a subset of the given set with sum equal to given <em>sum<\/em>.<span id=\"more-28860\"><\/span><\/p>\n<pre>Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9\r\nOutput:  True  \/\/There is a subset (4, 5) with sum 9.<\/pre>\n<p>Let isSubSetSum(int set[], int n, int sum) be the function to find whether there is a subset of set[] with sum equal to <em>sum<\/em>. n is the number of elements in set[].<\/p>\n<p>The isSubsetSum problem can be divided into two subproblems<br \/>\n\u2026a) Include the last element, recur for n = n-1, sum = sum \u2013 set[n-1]\n\u2026b) Exclude the last element, recur for n = n-1.<br \/>\nIf any of the above the above subproblems return true, then return true.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following is the recursive formula for isSubsetSum() problem.<\/p>\n<pre>isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum) || \r\n                           isSubsetSum(set, n-1, sum-set[n-1])\r\n<strong>Base Cases:<\/strong>\r\nisSubsetSum(set, n, sum) = false, if sum &gt; 0 and n == 0\r\nisSubsetSum(set, n, sum) = true, if sum == 0 \r\n<\/pre>\n<p>Following is naive recursive implementation that simply follows the recursive structure mentioned above.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ A recursive solution for subset sum problem<br\/>class subset_sum<br\/>{<br\/>    \/\/ Returns true if there is a subset of set[] with sum<br\/>        \/\/ equal to given sum<br\/>    static boolean isSubsetSum(int set[], int n, int sum)<br\/>    {<br\/>       \/\/ Base Cases<br\/>       if (sum == 0)<br\/>         return true;<br\/>       if (n == 0 &amp;&amp; sum != 0)<br\/>         return false;<br\/>      <br\/>       \/\/ If last element is greater than sum, then ignore it<br\/>       if (set[n-1] &gt; sum)<br\/>         return isSubsetSum(set, n-1, sum);<br\/>      <br\/>       \/* else, check if sum can be obtained by any of the following<br\/>          (a) including the last element<br\/>          (b) excluding the last element   *\/<br\/>       return isSubsetSum(set, n-1, sum) || <br\/>                                   isSubsetSum(set, n-1, sum-set[n-1]);<br\/>    }<br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int set[] = {3, 34, 4, 12, 5, 2};<br\/>          int sum = 9;<br\/>          int n = set.length;<br\/>          if (isSubsetSum(set, n, sum) == true)<br\/>             System.out.println(&quot;Found a subset with given sum&quot;);<br\/>          else<br\/>             System.out.println(&quot;No subset with given sum&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre> Found a subset with given sum<\/pre>\n<p>The above solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>We can solve the problem in Pseudo-polynomial time using Dynamic programming. <\/strong>We create a boolean 2D table subset[][] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n]\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ A Dynamic Programming solution for subset sum problem<br\/>class subset_sum<br\/>{<br\/>    \/\/ Returns true if there is a subset of set[] with sun equal to given sum<br\/>    static boolean isSubsetSum(int set[], int n, int sum)<br\/>    {<br\/>        \/\/ The value of subset[i][j] will be true if there <br\/>            \/\/ is a subset of set[0..j-1] with sum equal to i<br\/>        boolean subset[][] = new boolean[sum+1][n+1];<br\/>      <br\/>        \/\/ If sum is 0, then answer is true<br\/>        for (int i = 0; i &lt;= n; i++)<br\/>          subset[0][i] = true;<br\/>      <br\/>        \/\/ If sum is not 0 and set is empty, then answer is false<br\/>        for (int i = 1; i &lt;= sum; i++)<br\/>          subset[i][0] = false;<br\/>      <br\/>         \/\/ Fill the subset table in botton up manner<br\/>         for (int i = 1; i &lt;= sum; i++)<br\/>         {<br\/>           for (int j = 1; j &lt;= n; j++)<br\/>           {<br\/>             subset[i][j] = subset[i][j-1];<br\/>             if (i &gt;= set[j-1])<br\/>               subset[i][j] = subset[i][j] || <br\/>                                          subset[i - set[j-1]][j-1];<br\/>           }<br\/>         }<br\/>      <br\/>        \/* \/\/ uncomment this code to print table<br\/>         for (int i = 0; i &lt;= sum; i++)<br\/>         {<br\/>           for (int j = 0; j &lt;= n; j++)<br\/>              printf (&quot;%4d&quot;, subset[i][j]);<br\/>           printf(&quot;\\n&quot;);<br\/>         } *\/<br\/>      <br\/>         return subset[sum][n];<br\/>    }<br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int set[] = {3, 34, 4, 12, 5, 2};<br\/>          int sum = 9;<br\/>          int n = set.length;<br\/>          if (isSubsetSum(set, n, sum) == true)<br\/>             System.out.println(&quot;Found a subset with given sum&quot;);<br\/>          else<br\/>             System.out.println(&quot;No subset with given sum&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Found a subset with given sum<\/pre>\n<p>Time complexity of the above solution is O(sum*n).<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming &#8211; Subset Sum Problem &#8211; Dynamic Programming Given a set of non-negative integers, and a value sum, determine if there is a subset <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,70145,2139],"tags":[72846,72987,72985,72843,72844,72850,80975,80976,80977,70593,70616,74632,80972,72851],"class_list":["post-27160","post","type-post","status-publish","format-standard","hentry","category-coding","category-dynamic-programming","category-java","tag-dynamic-programming-in-data-structure","tag-dynamic-programming-in-java","tag-dynamic-programming-java","tag-dynamic-programming-problems","tag-dynamic-programming-software","tag-explain-dynamic-programming","tag-subset-sum-calculator","tag-subset-sum-in-c-program","tag-subset-sum-in-java-program","tag-subset-sum-problem","tag-subset-sum-problem-dynamic-programming","tag-subset-sum-problem-java","tag-subset-sum-problem-np-complete","tag-youtube-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27160","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27160"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27160\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27160"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27160"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27160"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}