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
- 40 lines of Python from the credited upstream file valid-binary-strings-with-cost-limit.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
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(object):6 def generateValidStrings(self, n, k):7 """8 :type n: int9 :type k: int10 :rtype: List[str]11 """12 def backtracking(total):13 if len(curr) == n:14 result.append("".join(curr))15 return16 curr.append('0')17 backtracking(total)18 curr.pop()19 if (not curr or curr[-1] == '0') and total+len(curr) <= k:20 curr.append('1')21 backtracking(total+(len(curr)-1))22 curr.pop()23 24 result, curr = [], []25 backtracking(0)26 return result27 28 29303132class Solution2(object):33 def generateValidStrings(self, n, k):34 """35 :type n: int36 :type k: int37 :rtype: List[str]38 """39 return ["".join('1' if mask&(1<<i) else '0' for i in xrange(n)) for mask in xrange(1<<n) if mask&(mask>>1) == 0 and sum(i for i in xrange(n) if mask&(1<<i)) <= k]40