leetcode 1039的Python解决方案与C ++解决方案

时间:2019-05-06 09:49:35

标签: python c++ dynamic-programming

Leetcode 1039

我已经用python编写了代码。

class Solution(object):
    def minScoreTriangulation(self, A):
        self.dp = [[-1]*len(A)]*len(A)
        ret = self.calc(A, 0, len(A)-1)
        return ret

    def calc(self, A, x, y):
        if math.ceil(y-x) < 2:
            return 0

        if self.dp[x][y] != -1:
            return self.dp[x][y]

        mn = sys.maxint
        for i in range(x+1, y):
            mn = min(mn, (self.calc(A, x, i) + self.calc(A, i, y) + A[x]*A[y]*A[i]))

        self.dp[x][y] = mn
        return mn

我还用相同的逻辑编写了C ++解决方案。

class Solution {
public:
    int minScoreTriangulation(vector<int>& A) {
        vector<int> row(A.size(), -1);
        vector<vector<int>> dp(A.size(), row);

        int ret =calc(dp, A, 0, A.size()-1);

        return ret;
    }

    int calc(vector<vector<int>>& dp, vector<int>& A, int x, int y)
    {
        if ((y-x) < 2)
            return 0;

        if(dp[x][y] != -1) return dp[x][y];

        int mn = INT_MAX;

        for( int i=x+1; i<y ; i++)
        {
            mn = min(mn, calc(dp, A, x, i)+calc(dp, A, i, y)+A[x]*A[y]*A[i]);
        }
        dp[x][y] =mn;
        return mn;
    }
};

python解决方案给了我错误的答案。 能否请您解释一下我的python解决方案有什么问题。

1 个答案:

答案 0 :(得分:2)

问题是这一行:

self.dp = [[-1]*len(A)]*len(A)

在python中,您不能使用这种方式来初始化2d数组,因为它将引用相同的[-1]*len(A),请更改为:

self.dp = [[-1]*len(A) for i in range(len(A))]

它将正常工作。

相关问题