子集和问题中的 Python 程序


在本文中,我们将了解下面给出的问题陈述的解决方案。

问题陈述- 给定一个数组中的非负整数集合和一个值和,我们需要确定给定集合中是否存在一个子集,其和等于给定和。

现在让我们在下面的实施中观察解决方案-

# 朴素方法

举例

def SubsetSum(set, n, sum) :
   # Base Cases
   if (sum == 0) :
      return True
   if (n == 0 and sum != 0) :
      return False
   # ignore if last element is > sum
   if (set[n - 1] > sum) :
      return SubsetSum(set, n - 1, sum);
   # else,we check the sum
   # (1) including the last element
   # (2) excluding the last element
   return SubsetSum(set, n-1, sum) or SubsetSum(set, n-1, sumset[n-1])
# main
set = [2, 14, 6, 22, 4, 8]
sum = 10
n = len(set)
if (SubsetSum(set, n, sum) == True) :
   print("Found a subset with given sum")
else :
   print("No subset with given sum")

输出

Found a subset with given sum

# 动态方法

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

举例

# maximum number of activities that can be performed by a single person
def Activities(s, f ):
   n = len(f)
   print ("The selected activities are:")
   # The first activity is always selected
   i = 0
   print (i,end=" ")
   # For rest of the activities
   for j in range(n):
      # if start time is greater than or equal to that of previous activity
      if s[j] >= f[i]:
         print (j,end=" ")
         i = j
# main
s = [1, 2, 0, 3, 2, 4]
f = [2, 5, 4, 6, 8, 8]
Activities(s, f)

输出

Found a subset with given sum

结论

在本文中,我们已经了解了如何为子集和问题制作一个 Python 程序

更新于: 20-Dec-2019

2K+ 浏览量

开启您的职业生涯

完成课程以获得认证

开始吧
广告