-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1447. Simplified Fractions.cpp
67 lines (50 loc) · 1.31 KB
/
1447. Simplified Fractions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#
/*
Link: https://leetcode.com/problems/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
*/
// Solution
/*
TC = O(n * n)
SC = O(1)
*/
class Solution {
public:
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
vector<string> simplifiedFractions(int n) {
vector<string> ans;
string s;
int i, j, temp;
for (i = 1; i < n; i++) {
for (j = i + 1; j <= n; j++) {
if(gcd(i, j) == 1) {
string x = to_string(i);
string y = to_string(j);
s = x + "/" + y;
ans.push_back(s);
}
}
}
return ans;
}
};