Medium级别的新题:给定正整数n, 以任意顺序、以字符串形式返回(0, 1)开区间内的所分母不超过n的所有最简分数。
数据范围: 1<=n<=100
例如: n = 1,返回空vector/
再如: n = 3, 返回{"1/2", "1/3", "2/3"}
分析:之前没有做这个题……无聊题。这么小的数据范围,直接n ^ 2暴力枚举,再用gcd判断互质,输出即可。
代码:
class Solution { int gcd(int x, int y) { return y ? gcd(y, x % y) : x; }public: vector<string> simplifiedFractions(int n) { vector<string> r; for (int i = 1; i <= n; ++i) { const string s = to_string(i); for (int j = 1; j < i; ++j) { if (gcd(i, j) == 1) { r.push_back(to_string(j) + "/" + s); } } } return r; }};