[编程题]最大和子矩阵
采用动态规划策略,python实现与C++实现等价。
Python 代码:
# -*- coding:utf-8 -*- class SubMatrix: def fun(self, tempList): maxVal=tempList[0] temp=tempList[0] i=1 while(i<len(tempList)): if temp<0: temp=tempList[i] else: temp+=tempList[i] maxVal=max(temp, maxVal) i+=1 return maxVal def sumOfSubMatrix(self, mat, n): # write code here maxAllVal=-1000000 for i in xrange(n): maxAllVal=max(maxAllVal, self.fun(mat[i])) for j in xrange(i+1, n): for k in xrange(n): mat[i][k]+=mat[j][k] maxAllVal=max(maxAllVal, self.fun(mat[i])) return maxAllVal a=[[-16,-23,-13,-24],[14,-22,28,16],[25,-2,19,-10],[6,9,-17,20]] b=4 #a=[[-6,13,-21,-19],[21,19,5,-22],[-16,10,0,-11],[-15,-4,-8,-15]] print SubMatrix().sumOfSubMatrix(a, b)
C++ 代码:
#include <vector> #include <iostream> using namespace std; class SubMatrix { public: int sumOfSubMatrix(vector<vector<int> > mat, int n) { int maxVal = -(1<<31); for(int i = 0; i < n; i++){ vector<int> temp = mat[i]; maxVal = max(maxVal,helper(temp)); for(int j = i + 1; j < n; j++){ for(int k = 0; k < n; k++){ temp[k] += mat[j][k]; } maxVal = max(maxVal,helper(temp)); } } return maxVal; } //找出该数组的最大子数组和 int helper(vector<int> &a){ int temp = a[0]; int maxVal = temp; for(int i = 1; i < a.size(); i++){ if(temp < 0){ temp = a[i]; }else{ temp +=a[i]; } if(temp > maxVal){ maxVal = temp; } } return maxVal; } }; int main() { SubMatrix X; vector< vector<int> > mat; vector<int> temp; temp.push_back(-16); temp.push_back(-23); temp.push_back(-13); temp.push_back(-24); mat.push_back(temp); vector<int> temp1; temp1.push_back(14); temp1.push_back(-22); temp1.push_back(28); temp1.push_back(16); mat.push_back(temp1); vector<int> temp2; temp2.push_back(25); temp2.push_back(-2); temp2.push_back(19); temp2.push_back(-10); mat.push_back(temp2); vector<int> temp3; temp3.push_back(6); temp3.push_back(9); temp3.push_back(-17); temp3.push_back(20); mat.push_back(temp3); int n=4; cout<<X.sumOfSubMatrix(mat, n)<<endl; return 0; }
本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址,还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注处,如有侵权请与博主联系。
如果未特殊标注则为原创,遵循 CC 4.0 BY-SA 版权协议。
posted on 2017-01-19 17:30 Angry_Panda 阅读(447) 评论(0) 编辑 收藏 举报