【发布时间】:2019-05-06 09:49:35
【问题描述】:
我用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 解决方案有什么问题吗?
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
你可能在错误的堆栈交换上,你应该去那里codereview.stackexchange.com
-
@BlueSheepToken 这绝对不是代码审查的主题。
-
@Peilonrayz 我的错,我是这么认为的。为什么不应该呢?它应该在哪个stackexchange上? (当然也不是这样)
-
@BlueSheepToken "Code Review is for open-ended questions about code that already works correctly (to the best of your knowledge). Questions seeking help about debugging or understanding code are off-topic for Code Review"。我只知道 Code Review 的规则,所以不能评论其他网站。
标签: python c++ dynamic-programming