Python 使用递归,I';我得到的答案比正确答案少一个
问题是: 给定一个包含所有正数且无重复数的整数数组,查找可能的组合数,这些组合相加可构成一个正整数目标 例如:Python 使用递归,I';我得到的答案比正确答案少一个,python,recursion,Python,Recursion,问题是: 给定一个包含所有正数且无重复数的整数数组,查找可能的组合数,这些组合相加可构成一个正整数目标 例如: nums = [1, 2, 3] target = 4 可能的组合方式有: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 注意,不同的序列被视为不同的组合 因此,输出为7 def组合sum4(nums:List[int],target:int)->int: 如果目标==0: 返回1 elif目标为1而
nums = [1, 2, 3]
target = 4
可能的组合方式有:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
注意,不同的序列被视为不同的组合
因此,输出为7
def组合sum4(nums:List[int],target:int)->int:
如果目标==0:
返回1
elif目标<0:
返回0
elif len(nums)==0:
返回1
其他:
返回组合SUM4(nums[1:],目标nums[0])+combinationSum4(nums[1:],目标)
输出是7,但我得到的是6。我想介绍另一种通过递归解决它的方法,请看以下内容:
m_nums = [1, 2, 3]
m_target = 4
def recursive_implementation(nums, target, cnt):
if target == 0:
return cnt+1
else:
for item in nums:
if item<=target:
cnt = recursive_implementation(nums, target-item, cnt)
return cnt
a = recursive_implementation(m_nums, m_target, 0)
print(a)
为了进行健全性检查,我还尝试了输入-1,2
target:4
选项包括:
(1,1,1,1)
(1,1,2)
(1,2,1)
(2,1,1)
(2,2)
# output of the recursion - 5
我想介绍另一种通过递归来解决它的方法,看看这个:
m_nums = [1, 2, 3]
m_target = 4
def recursive_implementation(nums, target, cnt):
if target == 0:
return cnt+1
else:
for item in nums:
if item<=target:
cnt = recursive_implementation(nums, target-item, cnt)
return cnt
a = recursive_implementation(m_nums, m_target, 0)
print(a)
为了进行健全性检查,我还尝试了输入-1,2
target:4
选项包括:
(1,1,1,1)
(1,1,2)
(1,2,1)
(2,1,1)
(2,2)
# output of the recursion - 5
我喜欢@YossiLevi的一般方法,但我会避免他额外的争论,只是做:
def combinationSum(numbers, target):
if target == 0:
return 1 # base case
count = 0
for number in numbers:
if number <= target:
count += combinationSum(numbers, target - number)
return count
print(combinationSum([1, 2, 3], 4))
def组合总和(数字、目标):
如果目标==0:
返回1#基本情况
计数=0
对于数字中的数字:
如果number我喜欢@YossiLevi的一般方法,但我会避免他的额外论点,只需做:
def combinationSum(numbers, target):
if target == 0:
return 1 # base case
count = 0
for number in numbers:
if number <= target:
count += combinationSum(numbers, target - number)
return count
print(combinationSum([1, 2, 3], 4))
def组合总和(数字、目标):
如果目标==0:
返回1#基本情况
计数=0
对于数字中的数字:
如果这个数字可能有帮助:这个:为什么<代码>目标=0 和<代码> LEN(NUMS)=0</代码>为1而不是0?因为空数组被认为是解决方案之一。因此,如果<代码> NUS= []]/COD>和<代码>目标=5 < /代码>,结果是1?UMM。我不确定这个问题没有具体说明。这可能有帮助:为什么代码< >目标=0 < /代码>和<代码> LEN(NUMS)=0 < /代码>为1而不是0?因为空数组被认为是解决方案之一。因此,如果<代码> NUS= []]/COD>和<代码>目标=5 < /代码>,结果是1?UMM。我不确定问题是否没有具体说明。非常感谢!非常感谢你!