Slight modification leads to code for combination sum II


  • 0
    C

    Re: My Python 92 ms solution
    If you compare this code with the above code, only slight modification was added. Please leave any of your comments!

    '''
    class Solution(object):
    def combinationSum2(self, candidates, target):

        ret = []
        candidates.sort()  # put in ascending order
      
        for i in range(len(candidates)):
            if i >=1 and candidates[i] == candidates[i-1]:
                continue
            num, rlist, s = candidates[i], [], []
            if num < target:
                rlist = self.combinationSum2(candidates[i+1:], target - num) # only count forward, not backward, no redundant count
                if rlist is not None:
                    for s in rlist:
                        s.append(num)
                        ret.append(s)
                continue
            elif num == target:
                rlist = [num]
                ret.append(rlist)
                continue
            else:  # i > target, break, given that candidates are in ascending order
                break
                
        return ret
    

    '''


Log in to reply
 

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