方法一
思路:统计所有组合,并求其最大公约数是否为1,只有最大公约数为1的组合才成立,然后按组成的分数大小顺序排序。
import java.util.*;
public class Main {
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] a = new int[n * n + 1][2];
int cnt = 0;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= i; j++) {
if (gcd(i, j) == 1) {
a[cnt][0] = i;
a[cnt][1] = j;
cnt++;
}
}
}
int[][] res = new int[cnt][2];
for (int i = 0; i < cnt; i++) {
res[i][0] = a[i][0];
res[i][1] = a[i][1];
}
Arrays.sort(res, (o1, o2) -> o1[1] * o2[0] - o2[1] * o1[0]);
for (int i = 0; i < cnt; i++) {
System.out.println(res[i][1] + "/" + res[i][0]);
}
}
}
方法二
思路:递归
import java.util.*;
public class Main {
static int n;
private static void dfs(int a, int b, int c, int d) {
if (a + c > n) {
return;
}
dfs(a, b, a + c, b + d);
System.out.println((b + d) + "/" + (a + c));
dfs(a + c, b + d, c, d);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("0/1");
dfs(1, 0, 1, 1);
System.out.println("1/1");
}
}
标签:递归,int,System,dfs,最大公约数,static,1360,out
From: https://www.cnblogs.com/he0707/p/18095385/lanqiaobei10