Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions leetcode/1401-1500/1447.Simplified-Fractions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# [1447.Simplified Fractions][title]

## Description
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".
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/simplified-fractions
[me]: https://github.com/kylesliu/awesome-golang-algorithm
24 changes: 22 additions & 2 deletions leetcode/1401-1500/1447.Simplified-Fractions/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
package Solution

func Solution(x bool) bool {
return x
import "fmt"

func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}

func Solution(n int) []string {
in := make(map[string]struct{})
for i := 2; i <= n; i++ {
for j := 1; j < i; j++ {
m := gcd(j, i)
in[fmt.Sprintf("%d/%d", j/m, i/m)] = struct{}{}
}
}
ans := make([]string, 0)
for i := range in {
ans = append(ans, i)
}
return ans
}
16 changes: 9 additions & 7 deletions leetcode/1401-1500/1447.Simplified-Fractions/Solution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package Solution

import (
"reflect"
"sort"
"strconv"
"testing"
)
Expand All @@ -10,18 +11,19 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs int
expect []string
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", 2, []string{"1/2"}},
{"TestCase2", 3, []string{"1/2", "1/3", "2/3"}},
{"TestCase3", 4, []string{"1/2", "1/3", "1/4", "2/3", "3/4"}},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
sort.Strings(got)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
Expand All @@ -30,10 +32,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading