LeetCode 3211. 生成不含相邻零的二进制字符串

直接dfs暴搜所有串,2^18=1024*256,时间上是允许的。然后判断串是否合法。

复制代码
 1 const int N = 19;
 2 bool path[N];
 3 class Solution {
 4 public:
 5     bool check(int n){
 6         for(int i=0;i<n-1;i++){
 7             if(path[i]==0&&path[i+1]==0)
 8                 return false;
 9         }
10         return true;
11     }
12     void dfs(int u,int& n,vector<string>& res){
13         if(u>=n){
14             if(check(n)){
15                 string s="";
16                 for(int i=0;i<n;i++)
17                     if(path[i])
18                         s+="1";
19                     else
20                         s+="0";
21                 res.push_back(s);
22             }
23             return ;
24         }
25         path[u]=0;
26         dfs(u+1,n,res);
27         path[u]=1;
28         dfs(u+1,n,res);
29     }
30     vector<string> validStrings(int n) {
31         vector<string> res;
32         dfs(0,n,res);
33         return res;
34     }
35 };
复制代码

 

posted on   greenofyu  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示