Python 40ms iterative solution


  • 0
    T
    class Solution:
    # @param {integer} k
    # @param {integer} n
    # @return {integer[][]}
    def combinationSum3(self, k, n):
        result = [[0]]
        for i in reversed(range(k)):
            level = []
            for r in result:
                total = r.pop()
                start = r[-1] if r else 0
                for j in range(start + 1, 10):
                    res = r + [j]
                    if total + j * (i + 1) > n:
                        break
                    elif i == 0:
                        if total + j == n:
                            level.append(res)
                    else:
                        res.append(total + j)
                        level.append(res)
            result = level
        return result

Log in to reply
 

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