Given a number n, find the number of ways to multiply n elements with an associative operation.
Input : 2 Output : 2 For a and b there are two ways to multiply them. 1. (a * b) 2. (b * a) Input : 3 Output : 12
Explanation(Example 2) :
For a, b and c there are 12 ways to multiply them. 1. ((a * b) * c) 2. (a * (b * c)) 3. ((a * c) * b) 4. (a * (c * b)) 5. ((b * a) * c) 6. (b * (a * c)) 7. ((b * c) * a) 8. (b * (c * a)) 9. ((c * a) * b) 10. (c * (a * b)) 11. ((c * b) * a) 12. (c * (b * a))
Approach : First, we try to find out the recurrence relation. From above examples, we can see h(1) = 1, h(2) = 2, h(3) = 12 . Now, for n elements there will be n – 1 multiplications and n – 1 parentheses. And, (a1, a2, …, an ) can be obtained from (a1, a2, …, a(n – 1)) in exactly one of the two ways :
- Take a multiplication (a1, a2, …, a(n – 1))(which has n – 2 multiplications and n – 2 parentheses) and insert the nth element ‘an’ on either side of either factor in one of the n – 2 multiplications. Thus, for each scheme for n – 1 numbers gives 2 * 2 * (n – 2) = 4 * (n – 2) schemes for n numbers in this way.
- Take a multiplication scheme for (a1, a2, .., a(n-1)) and multiply on left or right by (‘an’). Thus, for each each scheme for n – 1 numbers gives two schemes for n numbers in this way.
So after adding above two, we get, h(n) = (4 * n – 8 + 2) * h(n – 1), h(n) = (4 * n – 6) * h(n – 1). This recurrence relation with same initial value is satisfied by the pseudo-Catalan number. Hence, h(n) = (2 * n – 2)! / (n – 1)!
- Make all elements of an array equal with the given operation
- Minimum possible sum of array elements after performing the given operation
- Ways to sum to N using array elements with repetition allowed
- Ways of dividing a group into two halves such that two elements are in different groups
- Number of ways to remove elements to maximize arithmetic mean
- Number of ways to form an array with distinct adjacent elements
- Multiply two polynomials
- Efficient way to multiply with 7
- Program to multiply two matrices
- Multiply the given number by 2 such that it is divisible by 10
- Multiply Large Numbers represented as Strings
- Russian Peasant (Multiply two numbers using bitwise operators)
- Multiply two integers without using multiplication, division and bitwise operators, and no loops
- Smallest number to multiply to convert floating point to natural
- Find average of two numbers using bit operation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.