Two practices, a DP, a DFS, because this data is relatively small, so the DFS is acceptable in the full array of ways, but when the big time is not, so DP way to grasp, I here is the practice of DFS, online there are many people write DP, you can go to see, Especially when traversing to the right parenthesis, you need to think about it.
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;Chara[ -];intlen,ans,mark[ -];BOOLok () {intLena = strlen (a), tot =0; for(inti =0; I < lena;i++) { if(A[i] = ='(') Tot++; if(A[i] = =')') Tot--; if(A[i] = ='?') return false; if(Tot <0)return false; } if(Tot! =0)return false; return true;}voidDfsintNow ) { if(now = =Len) { if(OK ()) ans++; return; } A[mark[now]]='('; DFS ( now+1); A[mark[now]]=')'; DFS ( now+1);}intMain () { while(~SCANF ("%s", a)) { intLena =strlen (a); Len=0; for(inti =0; I < lena;i++) { if(A[i] = ='?') {Mark[len++] =i; }} ans=0; DFS (0); printf ("%d\n", ans); } return 0;}
Fzu 2030 parentheses problem