To generate all valid binary strings of length n with no adjacent zeros, we can use backtracking. At each step, we can always add ‘1’, but we can only add ‘0’ if the previous character is not ‘0’.
classSolution {
public List<String>generateStrings(int n) {
List<String> ans =new ArrayList<>();
dfs("", '1', n, ans);
return ans;
}
privatevoiddfs(String s, char last, int n, List<String> ans) {
if (s.length() == n) { ans.add(s); return; }
dfs(s +"1", '1', n, ans);
if (last !='0') dfs(s +"0", '0', n, ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fungenerateStrings(n: Int): List<String> {
val ans = mutableListOf<String>()
fundfs(s: String, last: Char) {
if (s.length == n) { ans.add(s); return }
dfs(s + "1", '1')
if (last !='0') dfs(s + "0", '0')
}
dfs("", '1')
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defgenerateStrings(self, n: int) -> list[str]:
ans: list[str] = []
defdfs(s: str, last: str):
if len(s) == n:
ans.append(s)
return dfs(s +'1', '1')
if last !='0':
dfs(s +'0', '0')
dfs('', '1')
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfngenerate_strings(n: i32) -> Vec<String> {
fndfs(s: String, last: char, n: i32, ans: &mut Vec<String>) {
if s.len() == n asusize {
ans.push(s);
return;
}
dfs(format!("{}1", s), '1', n, ans);
if last !='0' {
dfs(format!("{}0", s), '0', n, ans);
}
}
letmut ans =vec![];
dfs(String::new(), '1', n, &mut ans);
ans
}
}
⏰ Time complexity: O(2^n), as each position can be ‘1’ or ‘0’ (with constraints), so the number of valid strings is less than 2^n but still exponential.
🧺 Space complexity: O(2^n), for storing all valid strings.