File tree Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Original file line number Diff line number Diff line change @@ -206,12 +206,15 @@ string kth_balanced2(int n, int k) {
206
206
}
207
207
208
208
string ans;
209
- int depth = 0;
209
+ int shift, depth = 0;
210
+
210
211
stack<char> st;
211
212
for (int i = 0; i < 2*n; i++) {
213
+
212
214
// '('
213
- if (depth + 1 <= n) {
214
- int cnt = d[2*n-i-1][depth+1] << ((2*n-i-1-depth-1) / 2);
215
+ shift = ((2*n-i-1-depth-1) / 2);
216
+ if (shift >= 0 && depth + 1 <= n) {
217
+ int cnt = d[2*n-i-1][depth+1] << shift;
215
218
if (cnt >= k) {
216
219
ans += '(';
217
220
st.push('(');
@@ -222,8 +225,9 @@ string kth_balanced2(int n, int k) {
222
225
}
223
226
224
227
// ')'
225
- if (depth && st.top() == '(') {
226
- int cnt = d[2*n-i-1][depth-1] << ((2*n-i-1-depth+1) / 2);
228
+ shift = ((2*n-i-1-depth+1) / 2);
229
+ if (shift >= 0 && depth && st.top() == '(') {
230
+ int cnt = d[2*n-i-1][depth-1] << shift;
227
231
if (cnt >= k) {
228
232
ans += ')';
229
233
st.pop();
@@ -234,8 +238,9 @@ string kth_balanced2(int n, int k) {
234
238
}
235
239
236
240
// '['
237
- if (depth + 1 <= n) {
238
- int cnt = d[2*n-i-1][depth+1] << ((2*n-i-1-depth-1) / 2);
241
+ shift = ((2*n-i-1-depth-1) / 2);
242
+ if (shift >= 0 && depth + 1 <= n) {
243
+ int cnt = d[2*n-i-1][depth+1] << shift;
239
244
if (cnt >= k) {
240
245
ans += '[';
241
246
st.push('[');
You can’t perform that action at this time.
0 commit comments