377. Combination Sum IV, 377 combination
Problem
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
Nums= [1, 2, 3]Target= 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. therefore the output is7.
Analysis
According to the question, the subproblem can be expressed as F (I) = F (I) + F (I-nums [j]), where I starts from 1 to target, j is the subscript of the array, from 0 to nums. size (). The calculation result shows that the target is the maximum number of all combinations of [1, target]. The calculation of each target uses the exhaustive traversal of each nums element.
Code
Int combinationSum4 (vector <int> & nums, int target) {vector <int> V (target + 1, 0); int I, j; V [0] = 1; // V [0] is 1 because I-nums [j] = 0 V [I-nums [j] is successful once for (I = 1; I <= target; I ++) {for (j = 0; j <nums. size (); j ++) if (nums [j] <= I) V [I] + = V [I-nums [j];} return V [target];}View Code