LC.1155. Number of Dice Rolls With Target Sum

LC.1155. Number of Dice Rolls With Target Sum_第1张图片

class Solution1(object):
    def numRollsToTarget(self, d, f, target):
        """
        d: dice number
        f: 1~f numbe of a dice
        dp[i][j]表示用i 个dice 搞出 j 分的方法数
        初始化dp[0][0] = 0
        """
        m = pow(10, 9) + 7
        dp = [[0] * (target+1) for _ in range(d+1)]
        dp[0][0] = 1
        for i in range(1, len(dp)):
            for j in range(1, len(dp[0])):
                for k in range(1, f+1):
                    dp[i][j] = (dp[i][j] + dp[i-1][j-k]) % m if j >= k else dp[i][j]
        return dp[-1][-1]

class Solution2(object):
    def numRollsToTarget(self, d, f, target):
        """
        二维dp转一维节省空间
        """
        m = pow(10, 9) + 7
        dp = [0] * (target + 1)
        dp[0] = 1
        for _ in range(d):
            tmp = [0] * (target + 1)
            for i in range(len(dp)):
                for k in range(1, f+1):
                    if i - k >= 0:
                        tmp[i] = (tmp[i] + dp[i-k]) % m
            dp = tmp
        return dp[-1]

class Solution(object):
    def numRollsToTarget(self, d, f, target):
        """
        带记忆的递归
        """
        dictionary = {}
        m = pow(10, 9) + 7
        def DFS(d,f,target):
            if d == 0 or target == 0:
                if d == 0 and target == 0:
                    return 1
                else:
                    return 0
            key = str(d) + '_' + str(target)
            if key not in dictionary:
                result = sum([DFS(d-1, f, target - k) % m for k in range(1, f+1) if (target - k) >= 0] + [0]) % m
                dictionary[key] = result
            return dictionary[key]
        return DFS(d, f, target)

你可能感兴趣的:(LeetCode)