Note that there are some explanatory texts on larger screens.

plurals
  1. POHow many valid parenthesis combinations?
    primarykey
    data
    text
    <p>We have:</p> <ul> <li><p><code>n1</code> number of <code>{}</code> brackets , </p></li> <li><p><code>n2</code> number of <code>()</code> brackets , </p></li> <li><p><code>n3</code> number of <code>[]</code> brackets , </p></li> </ul> <p>How many different valid combination of these brackets we can have? </p> <p>What I thought: I wrote a brute force code in java (which comes in the following) and counted all possible combinations, I know it's the worst solution possible, </p> <p>(the code is for general case in which we can have different types of brackets)</p> <p>Any mathematical approach ? </p> <p>Note 1: valid combination is defined as usual, e.g. <code>{{()}}</code> : valid , <code>{(}){}</code> : invalid</p> <p>Note 2: let's assume that we have 2 pairs of <code>{}</code> , 1 pair of <code>()</code> and 1 pair of <code>[]</code>, the number of valid combinations would be 168 and the number of all possible (valid &amp; invalid) combinations would be 840</p> <pre><code>static void paranthesis_combination(char[] open , char[] close , int[] arr){ int l = 0; for (int i = 0 ; i &lt; arr.length ; i++) l += arr[i]; l *= 2; paranthesis_combination_sub(open , close , arr , new int[arr.length] , new int[arr.length], new StringBuilder(), l); System.out.println(paran_count + " : " + valid_paran_count); return; } static void paranthesis_combination_sub(char[] open , char[] close, int[] arr , int[] open_so_far , int[] close_so_far, StringBuilder strbld , int l){ if (strbld.length() == l &amp;&amp; valid_paran(open , close , strbld)){ System.out.println(new String(strbld)); valid_paran_count++; return; } for (int i = 0 ; i &lt; open.length ; i++){ if (open_so_far[i] &lt; arr[i]){ strbld.append(open[i]); open_so_far[i]++; paranthesis_combination_sub(open , close, arr , open_so_far , close_so_far, strbld , l); open_so_far[i]--; strbld.deleteCharAt(strbld.length() -1 ); } } for (int i = 0 ; i &lt; open.length ; i++){ if (close_so_far[i] &lt; open_so_far[i]){ strbld.append(close[i]); close_so_far[i]++; paranthesis_combination_sub(open , close, arr , open_so_far , close_so_far, strbld , l); close_so_far[i]--; strbld.deleteCharAt(strbld.length() -1 ); } } return; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload