【數學】B070_LC_最簡分數(枚舉 + gcd)

一、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;
    }
}

複雜度分析

  • 時間複雜度:O(n2)O(n^2)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章