
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combination Sum IV in C++
Suppose we have an integer array with all positive numbers and all elements are unique, find the number of possible combinations, so that if we add up, we will get positive integer target.
So if the array is [1, 2, 3] and the target is 4, then the possible combinations will be [[1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [1,3], [3,1], [2, 2]], so output will be 7.
To solve this, we will follow these steps −
- Suppose we have one recursive function called solve(), this is taking array, target and another array for dynamic programming tasks. The process will be like
- if target = 0, then return 1
- if dp[target] is not -1, then return dp[target]
- ans := 0
- for i in range 0 to nums
- if target >= nums[i]
- ans := ans + solve(nums, target – nums[i], dp)
- if target >= nums[i]
- set dp[target] := ans
- return ans
Example(C++)
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector <int> dp(target + 1, -1); return helper(nums, target, dp); } int helper(vector <int>& nums, int target, vector <int>& dp){ if(target == 0)return 1; if(dp[target] != -1)return dp[target]; int ans = 0; for(int i = 0; i < nums.size(); i++){ if(target >= nums[i]){ ans += helper(nums, target - nums[i], dp); } } return dp[target] = ans; } }; main(){ Solution ob; vector<int> v = {1,2,3}; cout << ob.combinationSum4(v, 4); }
Input
[1,2,3] 4
Output
7
Advertisements