이 기사에서는 아래 주어진 문제 설명에 대한 솔루션에 대해 알아볼 것입니다.
문제 설명 − 배열에 음이 아닌 정수 집합과 값 합계가 주어지면 주어진 합계와 동일한 합계를 가진 주어진 집합의 하위 집합이 있는지 확인해야 합니다.
이제 아래 구현에서 솔루션을 관찰해 보겠습니다 -
# 순진한 접근 방식
예시
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 프로그램을 만드는 방법에 대해 배웠습니다.