Medium - Simplified Fractions
https://leetcode.com/problems/simplified-fractions/description/
Simplified Fractions - LeetCode
Can you solve this real interview question? Simplified Fractions - Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. Ex
leetcode.com
문제 설명
Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.
- 1 <= n <= 100
예시
Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
Input: n = 3
Output: ["1/2","1/3","2/3"]
Input: n = 4
Output: ["1/2","1/3","1/4","2/3","3/4"]
Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".
풀이
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
ret = []
memo = {}
for bottom in range(2, n+1):
for top in range(1, bottom):
entry = f'{top}/{bottom}'
if entry not in memo:
ret.append(entry)
x = 2
while True:
future_top = top * x
future_bottom = bottom * x
if future_bottom > n:
break
future_dup = f'{future_top}/{future_bottom}'
memo[future_dup] = None
x += 1
return ret
분모와 분자가 서로소가 아닌 경우는 항상 중복이다.
두 수가 서로소임을 확인하는 방식은 GCD (Greatest Common Divisor)가 1인지 체크한다.
기본 라이브러리에 GCD를 체크하는 함수도 있고, 이외에도 GCD를 확인하는 방식들이 있다.
이 풀이에서는 N의 최대값이 100으로 상대적으로 작기 때문에, 분모가 N보다 작거나 같은 simplifiedFractions가 아닌 분수들을 딕셔너리에 저장하고, 이후 해당 값이 iterate 될 때 스킵하는 방식으로 문제를 해결한다.
사실 N이 워낙 작아서 메모고, GCD고 그냥 배열을 만들고 매번 중복이 있는지 확인해도 통과가 되는 것으로 보인다.