Why my code have the wrong answer?


  • 0
    L

    Why my code have the wrong answer? Can anyone help me analyze it?
    Thank you so much!

    '''
    def combinationSum3(self, k, n):
    """
    :type k: int
    :type n: int
    :rtype: List[List[int]]
    """
    candidates = [x for x in range(1,9)]

        res = []
        line = []
        self.helper(candidates, k, n, res, line)
        return res
        
    def helper(self, candidates, k, n, res, line):
        if len(line) == k and n == 0:
            res.append([x for x in line])
            return
        
        for i, x in enumerate(candidates):
            line.append(x)
            self.helper(candidates[i+1:], k, n-x, res, line) 
            line.pop()
    

    '''

    wrong answer is :

    Input:
    3
    15

    Output:
    [[1,6,8],[2,5,8],[2,6,7],[3,4,8],[3,5,7],[4,5,6]]

    Expected:
    [[1,5,9],[1,6,8],[2,4,9],[2,5,8],[2,6,7],[3,4,8],[3,5,7],[4,5,6]]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.