Binary Tree Level Order Traversal (Python)
Merge Two Sorted Lists (Python)

Combination Sum (Python)

kitt posted @ 2014年2月10日 02:04 in LeetCode , 2875 阅读

动态规划,依次求出target=1, 2, 3 ... N时的solution set, 后面的结果依赖于前面的结果。

 

class Solution:
    # @param {integer[]} candidates
    # @param {integer} target
    # @return {integer[][]}
    def combinationSum(self, candidates, target):
        dp = [[] for i in xrange(target + 1)]
        dp[0].append([]) # dp[0] must have content, an empty list, i.e. dp[0] = [[]]
        for i in xrange(1, target + 1):
            for number in candidates:
                if i >= number:
                    for L in dp[i - number]:
                        tmp = sorted(L + [number])
                        if tmp not in dp[i]: dp[i].append(tmp)
        return dp[target]
Avatar_small
Nicholas326 说:
2014年4月30日 07:20

第11行貌似可以不用dp[i-num]吧?

Avatar_small
kitt 说:
2015年6月03日 02:21

对的,已改,thx~ @Nicholas326:


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter