{"id":4287,"date":"2023-06-27T19:52:19","date_gmt":"2023-06-27T14:22:19","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4287"},"modified":"2023-06-27T19:57:41","modified_gmt":"2023-06-27T14:27:41","slug":"combination-sum","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/combination-sum\/","title":{"rendered":"Combination Sum (With Solution)"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#sample-test-cases-\">Sample Test Cases :<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#explanation-1\">Explanation 1:<\/a><\/li><li><a href=\"#explanation-2\">Explanation 2:<\/a><\/li><\/ul><\/ul><li><a href=\"#approach\">Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-implementation\">C++ Code Implementation<\/a><\/li><li><a href=\"#java-code-implementation\">Java Code Implementation<\/a><\/li><li><a href=\"#python-code-implementation\">Python Code Implementation<\/a><\/li><\/ul><li><a href=\"#practice-problem\">Practice Problem:<\/a><\/li><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-how-could-we-have-solved-the-problem-if-there-were-duplicates-in-the-array\">Q.1: How could we have solved the problem if there were duplicates in the array?<\/a><\/li><li><a href=\"#q2-why-can\u2019t-we-use-dynamic-programming-to-solve-this-problem\">Q.2: Why can\u2019t we use Dynamic Programming to solve this problem?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given an array, <strong>a[], <\/strong>consisting of distinct elements<strong>,<\/strong> and a target <strong>sum, <\/strong>find all the unique combinations in the array where the sum is equal to the target <strong>sum. <\/strong>The same number from the array may be chosen <strong>any<\/strong> number of times.<\/p>\n\n\n\n<h3 id=\"sample-test-cases-\"><span id=\"sample-test-cases\">Sample Test Cases :<\/span><\/h3>\n\n\n\n<p><strong>Input 1:<\/strong><\/p>\n\n\n\n<p>a[] = [1, 2], sum = 4<\/p>\n\n\n\n<p><strong>Output 1:<\/strong><\/p>\n\n\n\n[1, 1, 1, 1]\n\n\n\n[1, 1, 2]\n\n\n\n[2, 2]\n\n\n\n<h4 id=\"explanation-1\">Explanation 1:<\/h4>\n\n\n\n<p>All the possible combinations of elements that can sum up to <strong>sum<\/strong> are listed in the output.<\/p>\n\n\n\n<p><strong>Input 2:<\/strong><\/p>\n\n\n\n<p>a[] = [1, 3, 4, 5, 6], sum = 4<\/p>\n\n\n\n<p><strong>Output 2:<\/strong><\/p>\n\n\n\n[1, 1, 1, 1]\n\n\n\n[1, 3]\n\n\n\n[4]\n\n\n\n<h4 id=\"explanation-2\">Explanation 2:<\/h4>\n\n\n\n<p>All the possible combinations of elements that can sum up to <strong>sum<\/strong> are listed in the output.<\/p>\n\n\n\n<h2 id=\"approach\">Approach<\/h2>\n\n\n\n<p>The approach to solving this problem is to use a naive backtracking-based recursive approach. The recursion will work based on the following choices when we are at the <strong>ith <\/strong>index:<\/p>\n\n\n\n<ul><li>Take the ith element into the set under consideration.<\/li><li>Do not take the ith element into the set under consideration.<\/li><\/ul>\n\n\n\n<p>Based on the states of the recursion, the algorithm is described as follows:<\/p>\n\n\n\n<p><strong>Base Cases:<\/strong><\/p>\n\n\n\n<ul><li>If the <strong>sum<\/strong> == 0, at any moment in the recursive calls, we add that list to the result list and return from the function.<\/li><li>If the sum becomes negative or we reach the end of the array, we terminate that recursive call and return from that call.<\/li><\/ul>\n\n\n\n<p><strong>Recursion:<\/strong><\/p>\n\n\n\n<ul><li>Insert the element at the current position into the list, and recurse for the value <strong>sum := sum &#8211; a[index].<\/strong> Now pop this element from the list, and recurse for <strong>sum := sum.<\/strong> These recursive transitions correspond to the choices listed above.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"640\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Recursion Tree\"  class=\"wp-image-4431 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-1024x640.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-1024x640.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-300x188.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-768x480.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-1536x960.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-380x238.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-550x344.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-800x500.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1-1160x725.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Recursion-Tree-1.png 1600w\" ><\/figure>\n\n\n\n<p id=\"-code--implementation-\"><strong>Code \/ Implementation:<\/strong><\/p>\n\n\n\n<h3 id=\"c-code-implementation\">C++ Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void getAllCombinationsUtil(vector &amp;lt; int > &amp;amp; a, int sum, int currIndex, vector &amp;lt; vector &amp;lt; int >> &amp;amp; result, vector &amp;lt; int > &amp;amp; curr) {\n  if (sum == 0) {\n    result.push_back(curr);\n    return;\n  } else if (sum &amp;lt; 0 || currIndex == (int) a.size()) {\n    return;\n  } else {\n    curr.push_back(a[currIndex]);\n    getAllCombinationsUtil(a, sum - a[currIndex], currIndex, result, curr);\n    curr.pop_back();\n    getAllCombinationsUtil(a, sum, currIndex + 1, result, curr);\n  }\n}\nvector &amp;lt; vector &amp;lt; int >> getAllCombinations(vector &amp;lt; int > &amp;amp; a, int sum) {\n  vector &amp;lt; vector &amp;lt; int >> result;\n  vector &amp;lt; int > curr;\n  int index = 0;\n  getAllCombinationsUtil(a, sum, index, result, curr);\n  return result;\n}<\/pre>\n\n\n\n<h3 id=\"java-code-implementation\">Java Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static void getAllCombinationsUtil(int[] a, int sum, int currIndex, List &amp;lt; List &amp;lt; Integer >> result, List &amp;lt; Integer > curr) {\n  if (sum == 0) {\n    result.add(new ArrayList &amp;lt; > (curr));\n    return;\n  } else if (sum &amp;lt; 0 || currIndex == a.length) {\n    return;\n  } else {\n    curr.add(a[currIndex]);\n    getAllCombinationsUtil(a, sum - a[currIndex], currIndex, result, curr);\n    curr.remove((int) curr.size() - 1);\n    getAllCombinationsUtil(a, sum, currIndex + 1, result, curr);\n  }\n}\npublic static List &amp;lt; List &amp;lt; Integer >> getAllCombinations(int[] a, int sum) {\n  List &amp;lt; List &amp;lt; Integer >> result = new ArrayList &amp;lt; List &amp;lt; Integer >> ();\n  List &amp;lt; Integer > curr = new ArrayList &amp;lt; > ();\n  int index = 0;\n  getAllCombinationsUtil(a, sum, index, result, curr);\n  return result;\n}<\/pre>\n\n\n\n<h3 id=\"python-code-implementation\">Python Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def getCombinationsUtil(a, sum, currIndex, result, curr):\n    if sum == 0:\n        result.append(list(curr))\n        return\n    elif sum &amp;lt; 0 or currIndex == len(a):\n        return\n    else:\n        curr.append(a[currIndex])\n        getCombinationsUtil(a, sum - a[currIndex], currIndex, result, curr)\n        curr.pop()\n        getCombinationsUtil(a, sum, currIndex + 1, result, curr)\n\n\ndef getCombinations(a, sum):\n    result = []\n    curr = []\n    index = 0\n    getCombinationsUtil(a, sum, index, result, curr)\n    return result<\/pre>\n\n\n\n<p><strong>Complexity Analysis:<\/strong><\/p>\n\n\n\n<ul><li><strong>Time Complexity:<\/strong> Exponential<\/li><li><strong>Space Complexity:<\/strong> O(sum \/ minimum in array) \/\/ if recursion stack space is ignored<\/li><\/ul>\n\n\n\n<h2 id=\"practice-problem\">Practice Problem:<\/h2>\n\n\n\n<ul><li><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/combination-sum\/\" target=\"_blank\">Combination Sum<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-how-could-we-have-solved-the-problem-if-there-were-duplicates-in-the-array\"><span id=\"q-1-how-could-we-have-solved-the-problem-if-there-were-duplicates-in-the-array\">Q.1: How could we have solved the problem if there were duplicates in the array?<\/span><\/h3>\n\n\n\n<p><strong>Ans.<\/strong> We could remove the duplicates from the array and use the same recursive code to solve the problem.<\/p>\n\n\n\n<h3 id=\"q2-why-can\u2019t-we-use-dynamic-programming-to-solve-this-problem\"><span id=\"q-2-why-cant-we-use-dynamic-programming-to-solve-this-problem\">Q.2: Why can\u2019t we use Dynamic Programming to solve this problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans.<\/strong> In this problem, all the possible solutions are asked to be listed, rather than some optimal solution, so Dynamic Programming doesn\u2019t help us in this problem.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given an array, a[], consisting of distinct elements, and a target sum, find all the unique&hellip;\n","protected":false},"author":5,"featured_media":4432,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[610],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4287"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4287"}],"version-history":[{"count":6,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4287\/revisions"}],"predecessor-version":[{"id":20927,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4287\/revisions\/20927"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/4432"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}