1~9的数字可以组成3个3位数,设为:A,B,C, 现在要求满足如下关系:
B = 2 * A
C = 3 * A
请你写出A的所有可能答案,数字间用空格分开,数字按升序排列。
import java.util.Set; import java.util.TreeSet; public class Main { static int[] book = new int[9]; static int[] res = new int[9]; static StringBuilder a; static StringBuilder b; static StringBuilder c; static Set<String> set = new TreeSet<String>(); public static void main(String[] args) { dfs(0); for (String s : set) System.out.print(s + " "); } static void dfs(int idx) { if (idx == 9) { a = new StringBuilder(""); b = new StringBuilder(""); c = new StringBuilder(""); if (check()) set.add(a.toString()); return; } for (int i = 1; i <= 9; i++) { if (book[i - 1] == 0) { book[i - 1] = 1; res[idx] = i; dfs(idx + 1); book[i - 1] = 0; } } } private static boolean check() { a.append(res[0]).append(res[1]).append(res[2]); b.append(res[3]).append(res[4]).append(res[5]); c.append(res[6]).append(res[7]).append(res[8]); int numa = Integer.parseInt(a.toString()); int numb = Integer.parseInt(b.toString()); int numc = Integer.parseInt(c.toString()); return (numb == numa << 1) && (numc == numa * 3); } }