classSolution{public:intbuildWall(intheight,intwidth,vector<int>&bricks){constexprintkMod=1'000'000'007;// Stores the valid rows in bitmask.vector<int>rows;buildRows(width,bricks,0,rows);constintn=rows.size();// dp[i] := the number of ways to build `h` height walls with rows[i] in the// bottomvector<long>dp(n,1);// graph[i] := the valid neighbors of rows[i]vector<vector<int>>graph(n);for(inti=0;i<n;++i)for(intj=0;j<n;++j)if(!(rows[i]&rows[j]))graph[i].push_back(j);for(inth=2;h<=height;++h){vector<long>newDp(n);for(inti=0;i<n;++i)for(constintv:graph[i]){newDp[i]+=dp[v];newDp[i]%=kMod;}dp=std::move(newDp);}returnaccumulate(dp.begin(),dp.end(),0L)%kMod;}private:voidbuildRows(intwidth,constvector<int>&bricks,intpath,vector<int>&rows){for(constintbrick:bricks)if(brick==width)rows.push_back(path);elseif(brick<width){constintnewWidth=width-brick;buildRows(newWidth,bricks,path|1<<newWidth,rows);}}};
classSolution{publicintbuildWall(intheight,intwidth,int[]bricks){finalintMOD=1_000_000_007;// Stores the valid rows in bitmask.List<Integer>rows=newArrayList<>();buildRows(width,bricks,0,rows);finalintn=rows.size();// dp[i] := the number of ways to build `h` height walls With rows[i] in the bottomlong[]dp=newlong[n];// graph[i] := the valid neighbors of rows[i]List<Integer>[]graph=newList[n];Arrays.fill(dp,1);for(inti=0;i<n;++i)graph[i]=newArrayList<>();for(inti=0;i<n;++i)for(intj=0;j<n;++j)if((rows.get(i)&rows.get(j))==0)graph[i].add(j);for(inth=2;h<=height;++h){long[]newDp=newlong[n];for(inti=0;i<n;++i)for(finalintv:graph[i]){newDp[i]+=dp[v];newDp[i]%=MOD;}dp=newDp;}return(int)(Arrays.stream(dp).sum()%MOD);}privatevoidbuildRows(intwidth,int[]bricks,intpath,List<Integer>rows){for(finalintbrick:bricks)if(brick==width)rows.add(path);elseif(brick<width){finalintnewWidth=width-brick;buildRows(newWidth,bricks,path|1<<newWidth,rows);}}}
classSolution:defbuildWall(self,height:int,width:int,bricks:list[int])->int:MOD=1_000_000_007# Stores the valid rows in bitmask.rows=[]self._buildRows(width,bricks,0,rows)n=len(rows)# dp[i] := the number of ways to build `h` height walls with rows[i] in the bottomdp=[1]*n# graph[i] := the valid neighbors of rows[i]graph=[[]for_inrange(n)]fori,ainenumerate(rows):forj,binenumerate(rows):ifnota&b:graph[i].append(j)for_inrange(2,height+1):newDp=[0]*nforiinrange(n):forvingraph[i]:newDp[i]+=dp[v]newDp[i]%=MODdp=newDpreturnsum(dp)%MODdef_buildRows(self,width:int,bricks:list[int],path:int,rows:list[int],):forbrickinbricks:ifbrick==width:rows.append(path)elifbrick<width:newWidth=width-brickself._buildRows(newWidth,bricks,path|2<<newWidth,rows)
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! 😄