PHP 子集和问题程序
子集和问题是计算机科学和动态规划中的一个经典问题。给定一组正整数和一个目标和,任务是确定是否存在给定集合的一个子集,其元素之和等于目标和。
PHP 子集和问题程序
使用递归解法
示例
<?php
// A recursive solution for the subset sum problem
// Returns true if there is a subset of the set
// with a sum equal to the given sum
function isSubsetSum($set, $n, $sum)
{
// Base Cases
if ($sum == 0)
return true;
if ($n == 0 && $sum != 0)
return false;
// If the last element is greater than the sum, then ignore it
if ($set[$n - 1] > $sum)
return isSubsetSum($set, $n - 1, $sum);
// Check if the sum can be obtained by either including or excluding the last element
return isSubsetSum($set, $n - 1, $sum) ||
isSubsetSum($set, $n - 1, $sum - $set[$n - 1]);
}
// Driver Code
$set = array(1, 7, 4, 9, 2);
$sum = 16;
$n = count($set);
if (isSubsetSum($set, $n, $sum) == true)
echo "Found a subset with the given sum<br>";
else
echo "No subset with the given sum<br>";
$sum = 25;
$n = count($set);
if (isSubsetSum($set, $n, $sum) == true)
echo "Found a subset with the given sum.";
else
echo "No subset with the given sum.";
?>
输出
Found a subset with the given sum. No subset with the given sum.
在提供的示例中,集合为 [1, 7, 4, 9, 2],目标和分别为 16 和 25。第二次调用目标和为 25 返回 false,表明不存在加起来等于 25 的子集。因此,输出为“第一次调用中找到了具有给定和的子集。第二次调用中没有具有给定和的子集。”
使用动态规划的伪多项式时间算法
示例
<?php
// A Dynamic Programming solution for
// subset sum problem
// Returns true if there is a subset of
// set[] with sun equal to given sum
function isSubsetSum( $set, $n, $sum)
{
// The value of subset[i][j] will
// be true if there is a subset of
// set[0..j-1] with sum equal to i
$subset = array(array());
// If sum is 0, then answer is true
for ( $i = 0; $i <= $n; $i++)
$subset[$i][0] = true;
// If sum is not 0 and set is empty,
// then answer is false
for ( $i = 1; $i <= $sum; $i++)
$subset[0][$i] = false;
// Fill the subset table in bottom
// up manner
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $sum; $j++)
{
if($j < $set[$i-1])
$subset[$i][$j] =
$subset[$i-1][$j];
if ($j >= $set[$i-1])
$subset[$i][$j] =
$subset[$i-1][$j] ||
$subset[$i - 1][$j -
$set[$i-1]];
}
}
/* // uncomment this code to print table
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= sum; j++)
printf ("%4d", subset[i][j]);
printf("n");
}*/
return $subset[$n][$sum];
}
// Driver program to test above function
$set = array(8,15,26,35,42,59);
$sum = 50;
$n = count($set);
if (isSubsetSum($set, $n, $sum) == true)
echo "Found a subset with given sum.";
else
echo "No subset with given sum.";
?>
输出
Found a subset with given sum.
在提供的示例中,集合为 [8, 15, 26, 35, 42, 59],目标和为 50。函数调用 isSubsetSum($set, $n, $sum) 返回 true,表明集合中存在子集 [8, 42],其和等于目标和 50。因此,代码的输出将是“找到了具有给定和的子集”。
结论
总之,有两种不同的方法可以解决子集和问题。第一种解法是递归方法,它检查是否存在给定集合的子集,其和等于目标和。它利用回溯法来探索所有可能的组合。然而,这种解法在最坏情况下可能具有指数时间复杂度。
第二种解法利用动态规划,并自下而上地解决子集和问题。它构建一个表来存储中间结果,并有效地确定是否存在具有给定和的子集。这种方法的时间复杂度为 O(n*sum),使其比递归解法更有效。两种方法都可以用来解决子集和问题,而动态规划解法对于较大的输入更有效。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP