子集和問題中的 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

# 動態方法

舉例

# 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+ 瀏覽量

開啟您的職業生涯

完成課程以獲得認證

開始吧
廣告