设计 Excel 求和公式
Design Excel Sum Formula
题目详情
问题:设计 Excel 求和公式
考察:动态规划
来源:Citadel
链接:https://www.jointaro.com/interviews/questions/design-excel-sum-formula/
Your task is to design the basic function of an Excel-like program. You will be given a string array formula of size m x n representing the contents of the Excel sheet. The sheet is an m x n grid where each cell contains either an integer or a formula.
Specifically, you are to implement the Excel class:
Excel(int height, char width)Initializes the object with a sheet of the given dimensions.heightis a positive integer representing the height of the sheet.widthis a character representing the width of the sheet. The sheet is represented as anheight x widthgrid where the first row and column use 1-based indexing and are represented as integers and characters, respectively.
void set(int row, char column, int val)Changes the value atrowandcolumntoval.int get(int row, char column)Returns the value atrowandcolumn. If the cell contains a formula, evaluate the formula and return the result.int sum(int row, char column, string[] numbers)Sets the formula atrowandcolumnto be the sum of cells represented bynumbersand returns the result.- Each string in
numbersrepresents the location of a cell that contributes to the sum. - Each string has one of two formats:
"ColRow", whereColrepresents the column number as an uppercase letter andRowrepresents the row number as a string."ColRow1:ColRow2", whereColrepresents the column number as an uppercase letter,Row1represents the row number as a string, andRow2represents the end row number as a string. You can assume thatRow1 <= Row2.
- Each string in
Example:
Excel excel = new Excel(3, 'C');
// sheet is arranged as such:
// A1 = 1, B1 = 2, C1 = 3
// A2 = 4, B2 = 5, C2 = 6
// A3 = 7, B3 = 8, C3 = 9
excel.set(1, 'A', 2);
// sheet is arranged as such:
// A1 = 2, B1 = 2, C1 = 3
// A2 = 4, B2 = 5, C2 = 6
// A3 = 7, B3 = 8, C3 = 9
excel.sum(3, 'C', new String[] {"A1", "A1:B2"}); // return 10
// C3 = A1 + A1 + B1 + A2 + B2
excel.get(3, 'C'); // return 10
excel.set(2, 'B', 2);
// sheet is arranged as such:
// A1 = 2, B1 = 2, C1 = 3
// A2 = 4, B2 = 2, C2 = 6
// A3 = 7, B3 = 8, C3 = 9
excel.sum(3, 'C', new String[] {"A1", "A1:B2"}); // return 8
// C3 = A1 + A1 + B1 + A2 + B2
Constraints:
1 <= height <= 26'A' <= width <= 'Z'1 <= row <= height'A' <= column <= width-100 <= val <= 1001 <= numbers.length <= 5100 <= get(row, column) <= 200
解析
思路:每个单元格保存两类信息:直接值和公式依赖。设置值时清除公式;设置 SUM 时解析依赖区域并保存被引用单元格及次数。求值时递归计算依赖,或维护反向图做增量更新。
复杂度:朴素递归求值与依赖单元格数量成正比,空间为公式依赖图规模。