競賽程式設計簡單

矩陣鏈乘法

“矩陣鏈乘法”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 matrix_chain_order(p),它採用一個陣列 p 表示矩陣鏈的維度,使得矩陣 i 具有維度 p[i-1] x p[i]。求矩陣鏈相乘所需的最少標量乘法次數。

約束條件
  • 2 <= len(p) <= 100
  • 1 <= p[i] <= 500

範例

Example 1
Input
matrix_chain_order([40, 20, 30, 10, 30])
Output
26000
Explanation

There are 4 matrices of dimensions 40x20, 20x30, 30x10, and 10x30. The minimum operations are obtained by multiplying them in the order ((A(BC))D).

Example 2
Input
matrix_chain_order([10, 20, 30, 40, 30])
Output
30000
Explanation

The minimum number of scalar multiplications is 30000.

Need a Hint?
考慮使用動態程式特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。