sums[] = { 223, 224, 225, 225, 226, 226, 227, 227, 228, 229 } nums[n] = { 111, 112, 113, 114, 115 } a + b = 223 a + c = 224 a + d = 225 a + e = 226 b + c = 225 // 打破了第2条假设,不是按升序排序!
publicstatic String solution(int n, int[] sums) { ans = "Impossible"; fullArrange(sums, 0, n); // System.out.println(ans); return ans; } privatestaticvoidcheck(int n, int[] sums) { int[] nums = newint[n]; nums[0] = (int) Math.round((sums[0] + sums[1] - sums[n-1]) / 2.0); for (inti=1; i < n; i += 1) { nums[i] = sums[i-1] - nums[0]; } for (inti=0, k = 0; i < n; i += 1) { for (intj= i+1; j < n; j += 1) { if (nums[i] + nums[j] != sums[k++]) { return; } } } StringBuilderresult=newStringBuilder(); Arrays.sort(nums); for (int num: nums) { result.append(num + " "); } ans = newString(result.deleteCharAt(result.length()-1)); }
// 全排列,确定sums第k位的值 privatestaticvoidfullArrange(int[] sums, int k, int n) { if (k == sums.length) { check(n, sums); return; } for (inti= k, l = sums.length; i < l; i += 1) { swap(sums, i, k); fullArrange(sums, k + 1, n); swap(sums, i, k); } } privatestaticvoidswap(int[] a, int i, int j) { intt= a[i]; a[i] = a[j]; a[j] = t; } }