|
| 1 | +// Source : https://leetcode.com/problems/combination-sum-iv/ |
| 2 | +// Author : Calinescu Valentin |
| 3 | +// Date : 2016-08-07 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Given an integer array with all positive numbers and no duplicates, find the number |
| 8 | + * of possible combinations that add up to a positive integer target. |
| 9 | + * |
| 10 | + * Example: |
| 11 | + * |
| 12 | + * nums = [1, 2, 3] |
| 13 | + * target = 4 |
| 14 | + * |
| 15 | + * The possible combination ways are: |
| 16 | + * (1, 1, 1, 1) |
| 17 | + * (1, 1, 2) |
| 18 | + * (1, 2, 1) |
| 19 | + * (1, 3) |
| 20 | + * (2, 1, 1) |
| 21 | + * (2, 2) |
| 22 | + * (3, 1) |
| 23 | + * |
| 24 | + * Note that different sequences are counted as different combinations. |
| 25 | + * |
| 26 | + * Therefore the output is 7. |
| 27 | + * Follow up: |
| 28 | + * What if negative numbers are allowed in the given array? |
| 29 | + * How does it change the problem? |
| 30 | + * What limitation we need to add to the question to allow negative numbers? |
| 31 | + * |
| 32 | + ***************************************************************************************/ |
| 33 | + |
| 34 | + /* Solution |
| 35 | + * -------- |
| 36 | + * 1) Dynamic Programming - O(N * target) |
| 37 | + * |
| 38 | + * We notice that any sum S can be written as S_prev + nums[i], where S_prev is a sum of |
| 39 | + * elements from nums and nums[i] is one element of the array. S_prev is always smaller |
| 40 | + * than S so we can create the array sol, where sol[i] is the number of ways one can |
| 41 | + * arrange the elements of the array to obtain sum i, and populate it from 1 to target, |
| 42 | + * as the solution for i is made up of previously computed ones for numbers smaller than |
| 43 | + * i. The final answer is sol[target], which is returned at the end. |
| 44 | + * |
| 45 | + * Follow up: |
| 46 | + * |
| 47 | + * If the array contains negative numbers as well as positive ones we can run into a cycle |
| 48 | + * where some subset of the elements have sum 0 so they can always be added to an existing |
| 49 | + * sum, leading to an infinite number of solutions. The limitation that we need is a rule |
| 50 | + * to be followed by the input data, that which doesn't allow this type of subsets to exist. |
| 51 | + */ |
| 52 | +class Solution { |
| 53 | +public: |
| 54 | + int combinationSum4(vector<int>& nums, int target) { |
| 55 | + int sol[target + 1]; |
| 56 | + sol[0] = 1;//starting point, only 1 way to obtain 0, that is to have 0 elements |
| 57 | + for(int i = 1; i <= target; i++) |
| 58 | + { |
| 59 | + sol[i] = 0; |
| 60 | + for(int j = 0; j < nums.size(); j++) |
| 61 | + { |
| 62 | + if(i >= nums[j])//if there is a previously calculated sum to add nums[j] to |
| 63 | + sol[i] += sol[i - nums[j]]; |
| 64 | + } |
| 65 | + } |
| 66 | + return sol[target]; |
| 67 | + } |
| 68 | +}; |
0 commit comments