题目:
题解:
struct Next { int l, r, cl, cr; };void vec_push(char*** v, int* n, char* s) {if (!(*n & *n+1)) {*v = realloc(*v, sizeof(char*) * ((*n << 1) | 1));}(*v)[(*n)++] = s;
}void dfs(const char* s, int i, struct Next next[], int remain_l, int remain_r, int remove_l, int remove_r, char t[], int m, int depth, char*** ret, int* ret_size) {if (remove_l > remain_l || remove_r > remain_r) return;if (remove_l == remain_l && remove_r == remain_r) {while (s[i]) {if (s[i]!='(' && s[i]!=')') t[m++] = s[i];i++;}t[m] = 0;vec_push(ret, ret_size, strdup(t));return;}while (s[i]!='(' && s[i] !=')') t[m++] = s[i++];int c = next[i].cl + next[i].cr + i;int l = next[i].l, r = next[i].r;/* left */if (l<c && l-i <= remove_r) {t[m] = '(';dfs(s, l+1, next, remain_l-1, remain_r-(l-i), remove_l, remove_r-(l-i), t, m+1, depth+1, ret, ret_size);}if (depth && r<c && r-i <= remove_l) {t[m] = ')';dfs(s, r+1, next, remain_l-(r-i), remain_r-1, remove_l-(r-i), remove_r, t, m+1, depth-1, ret, ret_size);}if (next[i].cl <= remove_l && next[i].cr <= remove_r) {dfs(s, c, next, remain_l-next[i].cl, remain_r-next[i].cr, remove_l-next[i].cl, remove_r-next[i].cr, t, m, depth, ret, ret_size);}
}char ** removeInvalidParentheses(char * s, int* returnSize){/* 准备工作 */int n = strlen(s);int remove_l = 0, remove_r = 0;int remain_l = 0, remain_r = 0;for (int i=0; i!=n; ++i) {if (s[i] == '(') { remain_l++; remove_l++; }else if (s[i]==')') {remain_r++;if (remove_l) remove_l--;else remove_r++;}}/* next 计算 */struct Next next[n+1];next[n] = (struct Next) { .l = n, .r = n, .cl = 0, .cr = 0 };for (int i=n; i--;) {next[i] = next[i+1];if (s[i] == '(') { next[i].l = i; next[i].cl++; }else if (s[i]==')') { next[i].r = i; next[i].cr++; }else { next[i].cl = next[i].cr = 0; }}char** ret = NULL;*returnSize = 0;char t[n+1];dfs(s, 0, next, remain_l, remain_r, remove_l, remove_r, t, 0, 0, &ret, returnSize);return ret;
}