ยาก 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

สิ่งที่คุณจะได้เรียนรู้

  • Define a DP table over width and height
  • Try every horizontal and vertical cut
  • Reuse results for smaller rectangles

โจทย์

ดูฉบับแปล

On each move, choose one rectangle and cut all the way across it, parallel to a side, making two rectangles with positive integer side lengths. Continue until every piece is a square. Squares may have different sizes. Count cuts, not pieces.

Implement rectangle_cutting(height, width).

Input

height: The starting rectangle height.

width: The starting rectangle width.

Output

Return the minimum number of cuts.

เงื่อนไข

1 ≤ height, width ≤ 500. Rotation does not change the answer.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
width = 3
height = 2

ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
long long width = 3;
long long height = 2;

ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
long width = 3;
long height = 2;

ผลลัพธ์ที่คาดหวัง:
long expected = 2;

คำอธิบาย

Cut off a 2 × 2 square, leaving a 2 × 1 rectangle. One more cut splits the remainder into two unit squares.

ตัวอย่างที่ 2
อินพุต:
width = 4
height = 4

ผลลัพธ์ที่คาดหวัง:
expected = 0
อินพุต:
long long width = 4;
long long height = 4;

ผลลัพธ์ที่คาดหวัง:
long long expected = 0;
อินพุต:
long width = 4;
long height = 4;

ผลลัพธ์ที่คาดหวัง:
long expected = 0;

คำอธิบาย

The starting rectangle is already a square.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

A rectangle can be solved by splitting it into two smaller rectangles and combining their best answers.

คำใบ้ 2

Try every possible horizontal and vertical cut to find the minimum.

คำใบ้ 3

Memoization or a table is helpful because many subrectangles repeat.

ความซับซ้อนที่คาดหวัง

O(h*w*(h+w)) time, O(h*w) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก