https://leetcode.com/problems/range-sum-query-immutable/
class NumArray { public: vector<int> vec;
public:
NumArray(vector<int> &nums) {
if(nums.empty()) return;
else {
vec.push_back(nums[]);
for(int i=;i<nums.size();++i) vec.push_back(vec[i-] + nums[i]);
}
} int sumRange(int i, int j) {
if(i< || j>=vec.size()) return ;
if(i==) return vec[j];
else return vec[j] - vec[i-];
}
}; // Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
https://leetcode.com/problems/range-sum-query-2d-immutable/
class NumMatrix {
public:
vector<vector<int>> vec;
NumMatrix(vector<vector<int>> &matrix) {
if(matrix.size() == || matrix[].size() == ) return;
vec.resize(matrix.size());
for(int i=;i<vec.size();++i) vec[i].resize(matrix[].size()); vec[][] = matrix[][];
for(int col=;col<vec[].size();++col) vec[][col] = matrix[][col] + vec[][col-]; for(int row=;row<vec.size();++row) {
for(int col=;col<vec[row].size();++col) {
if(col == ) vec[row][col] = matrix[row][col];
else vec[row][col] = matrix[row][col] + vec[row][col-];
}
} for(int row=;row<vec.size();++row) {
for(int col=;col<vec[row].size();++col) {
vec[row][col] += vec[row-][col];
}
} for(int i=;i<vec.size();++i) {
for(int j=;j<vec[i].size();++j) cout<<vec[i][j]<<" ";
cout<<endl;
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(row1< || row2>=vec.size() || col1< || col2>=vec[].size()) return ; int leftTop = ;
if(row1 == || col1 == ) leftTop = ;
else if(row1 && col1) leftTop = vec[row1-][col1-]; int ret1 = ;
if(row1 == ) ret1 = vec[row2][col2];
else if(row1 > ) ret1 = vec[row2][col2] - vec[row1-][col2]; int ret2 = ;
if(col1 == ) ret2 = ret1;
else if(col1 > ) ret2 = ret1 - vec[row2][col1-] + leftTop; return ret2;
}
}; // Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);