Tutte le sfide
Difficile 1 risolta 100.0% di accettazione

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
height = 2
width = 3

Output atteso:
expected = 2
Input:
long long height = 2;
long long width = 3;

Output atteso:
long long expected = 2;
Input:
long height = 2;
long width = 3;

Output atteso:
long expected = 2;

Spiegazione

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

Esempio 2
Input:
height = 4
width = 4

Output atteso:
expected = 0
Input:
long long height = 4;
long long width = 4;

Output atteso:
long long expected = 0;
Input:
long height = 4;
long width = 4;

Output atteso:
long expected = 0;

Spiegazione

The starting rectangle is already a square.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

Memoization or a table is helpful because many subrectangles repeat.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 ННикита Python 954 ms - 4/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le recensioni AI. Accedi e risolvi la sfida per partecipare alla discussione.