1. Recursive Word Partitioning
Intuition
Recursively try ending the current line after each word that fits within width k.
Algorithm
- Define
solve(i). - If
i == n, return 0. - Initialize
minCost = inf,currentLen = 0. - For
j = iton - 1: -
currentLen += nums[j] + (j > i ? 1 : 0). - If
currentLen > k, break. -
cost = (j == n - 1) ? 0 : (k - currentLen)^2 + solve(j + 1). -
minCost = min(minCost, cost). - Return
minCost.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int i, const vector<int>& nums, int k) { int n = nums.size(); if (i == n) return 0; int minCost = 1e9, curLen = 0; for (int j = i; j < n; ++j) { curLen += nums[j] + (j > i ? 1 : 0); if (curLen > k) break; int cost = (j == n - 1) ? 0 : (k - curLen) * (k - curLen) + solve(j + 1, nums, k); minCost = min(minCost, cost); } return minCost; }public: int solveWordWrap(vector<int>& nums, int k) { return solve(0, nums, k); }}; int main() { Solution sol; vector<int> nums = {3, 2, 2, 5}; cout << "Min Cost: " << sol.solveWordWrap(nums, 6) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack