1. Recursive Permutation Search
Intuition
Recursively evaluate both choices at each step (making the next horizontal cut vs the next vertical cut) and find the minimal total cost.
Algorithm
- Step 1: Sort X and Y descending.
- Step 2: Define recursive function minCost(i, j, hPieces, vPieces).
- Step 3: If i == X.size() and j == Y.size(), return 0.
- Step 4: If i < X.size(), try horizontal cut: X[i] * vPieces + minCost(i + 1, j, hPieces + 1, vPieces).
- Step 5: If j < Y.size(), try vertical cut: Y[j] * hPieces + minCost(i, j + 1, hPieces, vPieces + 1).
- Step 6: Return the minimum of valid choices.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { long long solve(int i, int j, int hPieces, int vPieces, const vector<int>& X, const vector<int>& Y) { if (i == X.size() && j == Y.size()) return 0; long long ans = 1e18; if (i < X.size()) { ans = min(ans, (long long)X[i] * vPieces + solve(i + 1, j, hPieces + 1, vPieces, X, Y)); } if (j < Y.size()) { ans = min(ans, (long long)Y[j] * hPieces + solve(i, j + 1, hPieces, vPieces + 1, X, Y)); } return ans; }public: long long minimumCostOfBreaking(vector<int> X, vector<int> Y, int M, int N) { sort(X.rbegin(), X.rend()); sort(Y.rbegin(), Y.rend()); return solve(0, 0, 1, 1, X, Y); }}; int main() { Solution sol; vector<int> X = {2, 1, 3, 1, 4}; vector<int> Y = {4, 1, 2}; cout << "Min Cost: " << sol.minimumCostOfBreaking(X, Y, 6, 4) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^(M + N)) - Space complexity:
O(M + N)