[LeetCode] 1447. 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.

Example 1:

Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.

Example 2:

Input: n = 3
Output: ["1/2","1/3","2/3"]

Example 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".

Constraints:

  • 1 <= n <= 100

最简分数。

给你一个整数 n ,请你返回所有 0 到 1 之间(不包括 0 和 1)满足分母小于等于  n 的 最简 分数 。分数可以以 任意 顺序返回。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/simplified-fractions
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题,考察了最大公约数 gcd。LeetCode 中有不止一道题目考察了如何计算 gcd,需要留意。

题意不难理解,这里我们可以用暴力解两层 for 循环,去分别遍历除数和被除数。如何知道两者形成的数字是最简分数呢?就是用 gcd 的公式去判断两者的最大公约数是否是 1,如果是 1,那么这个分数一定是 unique 的,组合成字符串加入结果集即可。

时间 O(n ^ 2 * logn),其中计算最大公约数的复杂度是 O(log(min(x,y)))

空间 O(n^2) - return list, 计算 gcd 也使用了栈空间,花费是 O(logn)

Java实现

 1 class Solution {
 2     public List<String> simplifiedFractions(int n) {
 3         List<String> res = new ArrayList<>();
 4         // i 是被除数,j 是除数
 5         for (int i = 2; i <= n; i++) {
 6             for (int j = 1; j < i; j++) {
 7                 if (gcd(j, i) == 1) {
 8                     res.add(j + "/" + i);
 9                 }
10             }
11         }
12         return res;
13     }
14     
15     private int gcd(int x, int y) {
16         return x == 0 ? y : gcd(y % x, x);
17     }
18 }

 

LeetCode 题目总结

posted @ 2022-02-10 11:36  CNoodle  阅读(79)  评论(0编辑  收藏  举报