【发布时间】:2021-02-16 23:48:21
【问题描述】:
我希望在给定一个数组的情况下,找出总和为 S 的长度为 K 的子序列的数量。
示例输入:
a=[1,1,1,2,2] & K=2 & S=2
样本输出:
3 {because a[0],a[1]; a[1]a[2]; a[0]a[2] are only three possible for the case}
我尝试在 Python 中为初学者编写一个递归循环,但它没有按预期提供输出。请你帮我找到我可能存在的漏洞错过了。
def rec(k, sum1, arr, i=0):
#print('k: '+str(k)+' '+'sum1: '+str(sum1)) #(1) BaseCase:
if(sum1==0 and k!=0): # Both sum(sum1) required and
return 0 # numbers from which sum is required(k)
if(k==0 and sum1 !=0): # should be simultaneously zero
return 0 # Then required subsequences are 1
if(k==0 and sum1==0 ): #
return 1 #
base_check = sum1!=0 or k!=0 #(2) if iterator i reaches final element
if(i==len(arr) and base_check): # in array we should return 0 if both k
return 0 # and sum1 aren't zero
# func rec for getting sum1 from k elements
if(sum1<arr[0]): # takes either first element or rejects it
ans=rec(k-1,sum1,arr[i+1:len(arr)],i+1) # so 2 cases in else loop
print(ans) # i is taken in as iterator to provide array
else: # input to rec func from 2nd element of array
ans=rec(k-1, sum1-arr[0], arr[i+1:len(arr)],i+1)+rec(k, sum1, arr[i+1:len(arr)],i+1)
#print('i: '+str(i)+' ans: '+str(ans))
return(ans)
a=[1,1,1,2,2]
print(rec(2,2,a))
我仍然无法处理如何进行更改。一旦编写了这个正常的递归代码,我可能会采用 DP 方法。
【问题讨论】:
标签: python-3.x recursion substring