一、Problem
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. The fractions can be in any order.
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".
二、Solution
方法一:枚舉
不知道是否還有更優的解法…
class Solution {
int gcd(int a, int b) {
return a == 0 ? b : gcd(b%a,a);
}
public List<String> simplifiedFractions(int n) {
LinkedList<String> res = new LinkedList<>();
for (int i = 1; i <= n; i++)
for (int j = 1; j < i; j++) {
if (gcd(i, j) == 1)
res.add(j + "/" + i);
}
return res;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,