1. All-Pairs Swap Backtracking (O(N^(2K)))
Intuition
Iterate over all pairs (i, j) where i < j. If s[i] < s[j], swap them, compare with max, recurse with k - 1, and backtrack.
When to apply: Simple baseline to show complete exploration of swap space.
Algorithm
- If
k == 0, return. - Loop
ifrom 0 ton - 2: - - Loop
jfromi + 1ton - 1: - - If
s[i] < s[j]: - - Swap
s[i]ands[j]. - - If
s > maxStr,maxStr = s. - - Recurse
solve(s, k - 1). - - Swap back
s[i]ands[j].
#include <iostream>#include <string>#include <algorithm> using namespace std; class Solution { void solve(string& s, int k, string& maxStr) { if (k == 0) return; int n = s.length(); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (s[i] < s[j]) { swap(s[i], s[j]); if (s > maxStr) maxStr = s; solve(s, k - 1, maxStr); swap(s[i], s[j]); // backtrack } } } } public: string findMaximumNum(string s, int k) { string maxStr = s; solve(s, k, maxStr); return maxStr; }}; int main() { Solution sol; cout << sol.findMaximumNum("7599", 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^(2K))— There are O(N2) pairs to swap at each of the K recursive levels. - Space complexity:
O(K)— Recursion depth is K.