Hướng dẫn coin triangle python code
View Discussion Show Improve Article Save Article View Discussion Improve Article Save Article We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins. Examples: Input : N = 7 Output : 3 Maximum height will be 3, putting 1, 2 and then 3 coins. It is not possible to use 1 coin left. Input : N = 12 Output : 4 Maximum height will be 4, putting 1, 2, 3 and 4 coins, it is not possible to make height as 5, because that will require 15 coins.
Output: 4 Please refer complete article on Maximum height when coins are arranged in a triangle for more details! Pascal’s triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal’s triangle. Example: Input: N = 5 Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Method 1: Using nCr formula i.e. n!/(n-r)!r! After using nCr formula, the pictorial representation becomes: 0C0 1C0 1C1 2C0 2C1 2C2 3C0 3C1 3C2 3C3 Algorithm:
Implementation: Python3
Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time complexity: O(N2) Method 2: We can optimize the above code by the following concept of a Binomial Coefficient, the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1). C(line, i) = C(line, i-1) * (line - i + 1) / i Implementations: Python3
Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time complexity: O(N2) Auxiliary Space: O(1) because it is using constant space for variables Method 3: This is the most optimized approach to print Pascal’s triangle, this approach is based on powers of 11. 11**0 = 1 11**1 = 11 11**2 = 121 11**3 = 1331 Implementation: Python3
Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time Complexity: O(N) Auxiliary Space: O(1) as using constant variable However, this approach is applicable up to n=5 only. |