Approach
Depth-first search
For Valid Binary Strings with Cost Limit, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 57 lines of C++ from the credited upstream file valid-binary-strings-with-cost-limit.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<string> generateValidStrings(int n, int k) {8 vector<string> result;9 string curr;10 curr.reserve(n);11 const auto backtracking = [&](this auto&& dfs, int total) -> void {12 if (size(curr) == n) {13 result.emplace_back(curr);14 return;15 }16 curr.push_back('0');17 dfs(total);18 curr.pop_back();19 if ((empty(curr) || curr.back() == '0') && total + size(curr) <= k) {20 curr.push_back('1');21 dfs(total + (size(curr) - 1));22 curr.pop_back();23 }24 };25 26 backtracking(0);27 return result;28 }29};30 31323334class Solution2 {35public:36 vector<string> generateValidStrings(int n, int k) {37 vector<string> result;38 for (int mask = 0; mask < (1 << n); ++mask) {39 if (mask & (mask >> 1)) {40 continue;41 }42 int total = 0;43 string curr(n, '0');44 for (int i = 0; i < n; ++i) {45 if (mask & (1 << i)) {46 total += i;47 curr[i] = '1';48 }49 }50 if (total <= k) {51 result.emplace_back(move(curr));52 }53 }54 return result;55 }56};57