给你一个整数 n
,请你返回所有 0 到 1 之间(不包括 0 和 1)满足分母小于等于 n
的 最简 分数 。分数可以以 任意 顺序返回。
示例 1:
输入:n = 2 输出:["1/2"] 解释:"1/2" 是唯一一个分母小于等于 2 的最简分数。
示例 2:
输入:n = 3 输出:["1/2","1/3","2/3"]
示例 3:
输入:n = 4 输出:["1/2","1/3","1/4","2/3","3/4"] 解释:"2/4" 不是最简分数,因为它可以化简为 "1/2" 。
示例 4:
输入:n = 1 输出:[]
提示:
1 <= n <= 100
我们可以枚举分子
时间复杂度
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
return [
f'{i}/{j}'
for i in range(1, n)
for j in range(i + 1, n + 1)
if gcd(i, j) == 1
]
class Solution {
public List<String> simplifiedFractions(int n) {
List<String> ans = new ArrayList<>();
for (int i = 1; i < n; ++i) {
for (int j = i + 1; j < n + 1; ++j) {
if (gcd(i, j) == 1) {
ans.add(i + "/" + j);
}
}
}
return ans;
}
private int gcd(int a, int b) {
return b > 0 ? gcd(b, a % b) : a;
}
}
class Solution {
public:
vector<string> simplifiedFractions(int n) {
vector<string> ans;
for (int i = 1; i < n; ++i) {
for (int j = i + 1; j < n + 1; ++j) {
if (__gcd(i, j) == 1) {
ans.push_back(to_string(i) + "/" + to_string(j));
}
}
}
return ans;
}
};
func simplifiedFractions(n int) (ans []string) {
for i := 1; i < n; i++ {
for j := i + 1; j < n+1; j++ {
if gcd(i, j) == 1 {
ans = append(ans, strconv.Itoa(i)+"/"+strconv.Itoa(j))
}
}
}
return ans
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
function simplifiedFractions(n: number): string[] {
const ans: string[] = [];
for (let i = 1; i < n; ++i) {
for (let j = i + 1; j < n + 1; ++j) {
if (gcd(i, j) === 1) {
ans.push(`${i}/${j}`);
}
}
}
return ans;
}
function gcd(a: number, b: number): number {
return b === 0 ? a : gcd(b, a % b);
}
impl Solution {
fn gcd(a: i32, b: i32) -> i32 {
match b {
0 => a,
_ => Solution::gcd(b, a % b),
}
}
pub fn simplified_fractions(n: i32) -> Vec<String> {
let mut res = vec![];
for i in 1..n {
for j in i + 1..=n {
if Solution::gcd(i, j) == 1 {
res.push(format!("{}/{}", i, j));
}
}
}
res
}
}