可以采用程序枚举的方式穷举:
首先判断==24的只有两种可能,
在判断==136的只有1中可能
在判断==73的时候剔除掉 24,136入围的答案
依次类推....
答案:
//key:25611 list:[2, 5, 6, 11]===>24
//key:8182324 list:[8, 18, 23, 24]==>73
/key:17354143 list:[17, 35, 41, 43]===>136
//key:9193031 list:[9, 19, 30, 31]==>89
Java Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
package org.master.common;
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestAdd { public static void main( String[] args) { Integer[] arr = { 11, 2, 5, 6, 17, 18, 30, 8, 19, 35, 31, 43, 41, 24, 9, 23 }; Map< String, List<Integer>> map = new HashMap<>(); for ( int i = 0; i < arr.length; i++) { List<Integer> list = new ArrayList<>(); Integer a = arr[i]; for ( int j = 0; j < arr.length; j++) { if (j == i) { continue; } Integer b = arr[j]; for ( int m = 0; m < arr.length; m++) { if (m == i || m == j) { continue; } Integer c = arr[m]; for ( int n = 0; n < arr.length; n++) { if (n == i || n == j || n == m) { continue; } Integer d = arr[n]; Integer sum = a + b + c + d; //key:2589 list:[2, 5, 8, 9] // { // key:6181930 list:[6, 18, 19, 30] // key:6171931 list:[6, 17, 19, 31] // } //key:25611 list:[2, 5, 6, 11]===>24 // { // key:8182324 list:[8, 18, 23, 24] // key:8171830 list:[8, 17, 18, 30] // key:9172324 list:[9, 17, 23, 24] // } //key:8182324 list:[8, 18, 23, 24]==>73 //key:17354143 list:[17, 35, 41, 43]===>136 //key:9193031 list:[9, 19, 30, 31]==>89 boolean flag = valide( new Integer[] { 2, 5, 6, 11, 17, 35, 41, 43, 8, 18, 23, 24}, a, b, c, d); if(!flag) { continue; } //修改这个值--使用程序去完成计算【24,73,136,89】 if (sum == 89) { list.add(a); list.add(b); list.add(c); list.add(d); Collections.sort(list); String key = getKey(list); map.put(key, list); list = new ArrayList<>(); } } } } } for ( String key : map.keySet()) { System.out.println( "key:" + key + " list:" + map.get(key)); } } private static boolean valide(Integer[] arrays, Integer a, Integer b, Integer c, Integer d) { for( int i = 0; i < arrays.length; i++) { if(a == arrays[i] || b == arrays[i] || c == arrays[i] || d == arrays[i]) { return false; } } return true; } private static String getKey(List<Integer> list) { StringBuffer sb = new StringBuffer(); for ( int i = 0; i < list.size(); i++) { sb.append(list.get(i)); } return sb.toString(); } } |