/** * Determine if an array can k-sum any of its elements to equal $t. This works by iterating through each element of the * array and then looking at the value $k. If $k is > 3 the function recursively calls itself, passing $t - $number as * the value to look for and $k - 1 as the number of elements needed for the sum. Eventually the base case where $k = 2 * is reached and then hasTwoSum is used to determine if two elements in the array can sum to the value of $t at the * time. The boolean value is then returned back up the stack to get the result. Obviously at very large values for $k * this is time consuming because recursive calls are made at every level for every element in the array. * * @param int[] $array * @param int $t * @param int $k * @return bool */ function hasKSumRecursive($array, $t, $k) { foreach ($array as $number) { if ($k > 3) { if (hasKSumRecursive($array, $t - $number, $k - 1)) { return true; } } elseif (hasTwoSum($array, $t - $number)) { return true; } } return false; }
/** * Determine if an array can three sum any of its elements to equal $t. This works by going through each element and * determining if there is a two sum that will equal $t - $number. If there is, a three sum can be achieved by adding * $number. * * i.e. * If the input array is [1, 2, 3] and t is 5 * * <<< FOREACH LOOP BEGIN >>> * * Iteration 1: * $number = 1 * Is there a two sum that equals 4? Yes, 1 + 3 * * <<< FOREACH LOOP TERMINATION: function return >>> * * return true * * @param int[] $array * @param int $t * @return bool */ function hasThreeSum($array, $t) { if (empty($array)) { throw new \InvalidArgumentException('The input $array cannot be empty'); } if ($t > PHP_INT_MAX || $t < (PHP_INT_MAX + 1) * -1) { throw new \InvalidArgumentException('$t must be between ' . (PHP_INT_MAX + 1) * -1 . ' and ' . PHP_INT_MAX); } asort($array); foreach ($array as $number) { if (hasTwoSum($array, $t - $number)) { return true; } } return false; }