在我的“组合和”解决方案中找不到错误

时间:2020-08-27 18:07:46

标签: python algorithm

可以在leetcode处找到问题。 我为我的错误在哪里以及为什么我的解决方案无法产生正确的输出而烦恼。我花了几个小时,仍然无法理解。有人可以帮忙吗? 我的问题是在_rec函数的最后两行中,我试图说明允许多次从数组添加同一项目的情况。

我的解决方案:

class Solution:
    def _rec(self, arr, sums, i, all_arrs):
        if sums == 0:
            all_arrs.append(arr[i+1:])
            return
        
        if sums < 0 or i < 0:
            return

        #we can include current number at index i 
        withi = self._rec(arr, sums-arr[i], i-1, all_arrs) 
        
        #or not include it
        arr_copy = arr.copy()
        arr_copy.pop(i) # since we delete higher indices it won't affect lower indices 
        withouti = self._rec(arr_copy, sums, i-1, all_arrs)
        
        #to account on "The same repeated number may be chosen from candidates unlimited number of times."
        arr.append(arr[i])
        repeati = self._rec(arr, sums-arr[i], i, all_arrs)
        
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        final_arr = []
        self._rec(candidates, target, len(candidates)-1, final_arr)
        return final_arr

问题 给定一组候选编号(候选)(无重复)和目标编号(目标),找到候选编号求和的所有唯一组合。

可以从候选人无限制的次数中选择相同的重复号码。

注意:

所有数字(包括目标)将为正整数。 解决方案集不得包含重复的组合。 范例1:

输入:candidates = [2,3,6,7], target = 7, 一个解决方案集是:

[
  [7],
  [2,2,3]
]

示例2:

输入:候选人= [2,3,5],目标= 8 一个解决方案集是:

[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
 

约束:

1 <= candidates.length <= 30
1 <= candidates[i] <= 200
Each element of candidate is unique.
1 <= target <= 500


Output
[[7],[2,3,3,2],[3,3,2,2],[2,3,2,2,3,2,2],[3,2,2,3,2,2,2],[7]]

Expected
[[2,2,3],[7]]

注意:我知道可以通过动态编程对其进行优化,但是我现在只是想使递归起作用。

1 个答案:

答案 0 :(得分:-1)

而不是总是转到数组中的下一个数字,只有在达到或超过目标总和时才转到下一个数字。

因此,在2,3,5和8的情况下,您得到

2 = 2
2+2 = 4
2+2+2 = 6
2+2+2+2 = 8

得到答案,现在尝试下一个号码

2+2+2+3 = 9

太大,请尝试下一个号码

2+2+2+5 = 11

完整循环就像

2
2+2
2+2+2
2+2+2+2 met
2+2+2+3 exceeded
2+2+2+5 exceeded
2+2+3
2+2+3+3 exceeded (don't do 2 again since we already tried 2+2+2+3 which would be the same)
2+2+3+5 exceeded
2+2+5 exceeded
2+3
2+3+3 met
2+3+5 exceeded
2+5
2+5+5 exceeded
3
3+3
3+3+3 exceeded
3+3+5 exceeded
3+5 met
5
5+5 exceeded
complete