返回题库

设计 Excel 求和公式

Design Excel Sum Formula

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:设计 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.
    • height is a positive integer representing the height of the sheet.
    • width is a character representing the width of the sheet. The sheet is represented as an height x width grid 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 at row and column to val.
  • int get(int row, char column) Returns the value at row and column. If the cell contains a formula, evaluate the formula and return the result.
  • int sum(int row, char column, string[] numbers) Sets the formula at row and column to be the sum of cells represented by numbers and returns the result.
    • Each string in numbers represents the location of a cell that contributes to the sum.
    • Each string has one of two formats:
      • "ColRow", where Col represents the column number as an uppercase letter and Row represents the row number as a string.
      • "ColRow1:ColRow2", where Col represents the column number as an uppercase letter, Row1 represents the row number as a string, and Row2 represents the end row number as a string. You can assume that Row1 <= Row2.

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 <= 100
  • 1 <= numbers.length <= 5
  • 100 <= get(row, column) <= 200
解析

思路:每个单元格保存两类信息:直接值和公式依赖。设置值时清除公式;设置 SUM 时解析依赖区域并保存被引用单元格及次数。求值时递归计算依赖,或维护反向图做增量更新。

复杂度:朴素递归求值与依赖单元格数量成正比,空间为公式依赖图规模。