zoukankan      html  css  js  c++  java
  • 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. The fractions can be 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".

    Example 4:

    Input: n = 1
    Output: []
    

    Constraints:

    • 1 <= n <= 100
    class Solution {
        public List<String> simplifiedFractions(int n) {
            List<String> res = new ArrayList();
            if(n == 1) return new ArrayList();
            int k = n;
            while(k > 1){
                int t = k - 1; 
                while(t >= 1){
                    if(gcd(k, t) != 1){
                    t--;
                    continue;
                }
                    String sb = t + "/" + k;
                    res.add(sb);
                    t--;
                }
                k--;
            }
            return res;
        }
        public int gcd(int num1, int num2){
            int gcd = 1;
            for(int i = 1; i <= num1 && i <= num2; i++)
            {
                if(num1%i==0 && num2%i==0)
                    gcd = i;
            }
            return gcd;
        }
    }

    狗急跳墙做法,遇到gcd不是1就continue,否则就添加到res中

    class Solution {
        
        int gcd(int a, int b) {
            return b != 0 ? gcd(b, a % b) : a;
        }
        
        public List<String> simplifiedFractions(int n) {
            List<String> res = new ArrayList<>();
            for(int i = 1; i <= n; ++i) {
                for(int j = i + 1; j <= n; ++j) {
                    if(gcd(i, j) > 1) continue;
                    StringBuilder sb = new StringBuilder();
                    sb.append(i).append('/').append(j);
                    res.add(sb.toString());
                }
            }
            return res;
        }
    }

    简便写法

    https://leetcode.com/problems/simplified-fractions/discuss/635685/Java-Clean-code-Use-GCD-w-Video-solution-explaining-intuition

  • 相关阅读:
    Shared variable in python's multiprocessing
    File checksum
    Windows createprocess linux fork
    人工调用系统调用
    如何提高团队开发效率
    Redis' High Availability
    并发MD5计算方法
    开博宣言
    NYOJ 55 懒省事的小明
    HDU 1237 简单计算器
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12903580.html
Copyright © 2011-2022 走看看