|
| 1 | +/** |
| 2 | + * 544. Output Contest Matches |
| 3 | + * https://leetcode.com/problems/output-contest-matches/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * During the NBA playoffs, we always set the rather strong team to play with the rather weak |
| 7 | + * team, like making the rank 1 team play with the rank nth team, which is a good strategy to |
| 8 | + * make the contest more interesting. |
| 9 | + * |
| 10 | + * Given n teams, return their final contest matches in the form of a string. |
| 11 | + * |
| 12 | + * The n teams are labeled from 1 to n, which represents their initial rank (i.e., Rank 1 is |
| 13 | + * the strongest team and Rank n is the weakest team). |
| 14 | + * |
| 15 | + * We will use parentheses '(', and ')' and commas ',' to represent the contest team pairing. |
| 16 | + * We use the parentheses for pairing and the commas for partition. During the pairing process |
| 17 | + * in each round, you always need to follow the strategy of making the rather strong one pair |
| 18 | + * with the rather weak one. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @return {string} |
| 24 | + */ |
| 25 | +var findContestMatch = function(n) { |
| 26 | + const teams = Array.from({ length: n }, (_, i) => (i + 1).toString()); |
| 27 | + return pairTeams(teams); |
| 28 | + |
| 29 | + function pairTeams(arr) { |
| 30 | + if (arr.length === 1) return arr[0]; |
| 31 | + |
| 32 | + const nextRound = []; |
| 33 | + for (let i = 0; i < arr.length / 2; i++) { |
| 34 | + nextRound.push(`(${arr[i]},${arr[arr.length - 1 - i]})`); |
| 35 | + } |
| 36 | + |
| 37 | + return pairTeams(nextRound); |
| 38 | + } |
| 39 | +}; |
0 commit comments