今天摆渡三面的一道题,可惜差一点就答出来了,尝试了等差数列,等比数列没深入尝试,晚上边聊天边敲代码,代码写得不漂亮,但能实现基本功能,如下:
//Jay 2011.06.01 import java.util.*; public class FindNums { static final Set<Integer> resultOfAddOrSub(int[] arr) { Set<Integer> set = new HashSet<Integer>(); Set<Integer> setTemp = new HashSet<Integer>(); set.add(0); for (int i = 0; i < 4; i++) { for (int j : set) { setTemp.add(j + arr[i]); setTemp.add(j - arr[i]); setTemp.add(arr[i]); } set.addAll(setTemp); setTemp.clear(); } return set; } public static void main(String[] args) { Set<Integer> set; Set<Integer> allNum = new HashSet<Integer>(); for (int i = 1; i <= 40; i++) { allNum.add(i); } int[] arr = { 1, 2, 3, 4 }; for (int i1 = 0; i1 < 40; i1++) for (int i2 = i1; i2 < 40; i2++) for (int i3 = i2; i3 < 40; i3++) for (int i4 = i3; i4 < 40; i4++) { if (i1 != i2 && i1 != i3 && i1 != i4 && i2 != i3 && i3 != i4) { arr[0] = i1; arr[1] = i2; arr[2] = i3; arr[3] = i4; set = resultOfAddOrSub(arr); if (set.containsAll(allNum)) { System.out.println(set); System.out.print("The result is:"); for (int i : arr) System.out.print(" " + i); } } } } }
输出结果:
[0, -31, 1, -32, 2, -29, 3, -30, 4, -27, 5, -28, 6, -25, 7, -26, 8, -23, 9, -24, 10, -21, 11, -22, 12, -19, 13, -20, -17, 14, -18, 15, -16, 17, -15, 16, 19, -14, 18, -13, 21, -12, 20, -11, 23, -10, 22, -9, 25, -8, 24, -7, 27, -6, 26, -5, 29, -4, 28, -3, 31, -2, 30, -1, 34, 35, 32, 33, 38, 39, 36, 37, 40, -38, -37, -40, -39, -34, -33, -36, -35]
The result is: 1 3 9 27