定义整型数组,例如
int a[]={1,2,3,6,7,4,5,2,1}
再定义一个整型int sum = 0,sum的值为数组a中所有加起来和为sum的所有元素集合。例如当sum=5时,输出{5},{1,4},{2,3},{2,2,1},{1,1,3}
--------------------------------------------------------------------------------
思路:
1. 先对数组进行排序,a[] = {1,1,2,2,3,4,5,6,7}
2. 找到比sum大的元素序号,作为新的数组长度a[] = {1,1,2,2,3,4,5}
3. 从新的数组尾部开始向前累加,遍历一轮后,数组长度减一,继续轮询
a) 如果累加当前元素后,仍然小于sum,记录此元素,继续向前
b) 如果累加当前元素后,等于sum,记录此元素,并输出这个成功的集合;剔除当前元素,继续向前累加
c) 如果累加当前元素后,大于sum,剔除当前元素,继续向前累加
4. 输出的集合会有重复的情况,处理重复
void getCollections(int sum, int[] list) {
int[] array = new int[list.length];
for (int i = 0; i < array.length; i++) {
array[i] = list[i];
}
quickSort(array, 0, array.length);
int newlen = 0;
for (int i = 0; i < array.length; i++) {
newlen = i;
if (array[i] > sum) {
break;
}
}
if (newlen == 0) {
return;
}
HashSet<String> result = new HashSet<String>();
for (int i = newlen - 1; i >= 0; i--) {
int temp = 0;
StringBuilder builder = new StringBuilder();
for (int j = i; j >=0; j--) {
temp +=array[j];
if (temp < sum) {
builder.append(array[j] + " ");
} else if (temp == sum) {
if (!result.contains(builder.toString() + array[j])) {
result.add(builder.toString() + array[j]);
}
temp -= array[j];
} else {
temp -= array[j];
}
}
}
Iterator<String> i = result.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
public void quickSort(int[] array, int begin, int end) {
if (begin >= 0 && begin < end && end <= array.length) {
int index = partition(array, begin, end);
quickSort(array, begin, index - 1);
quickSort(array, index + 1, end);
}
}
public int partition(int[] arry, int begin, int end) {
int i = begin - 1;
for (int j = begin; j < end - 1; ++j) {
if (arry[j] < arry[end - 1]) {
++i;
int temp = arry[i];
arry[i] = arry[j];
arry[j] = temp;
}
}
++i;
int temp = arry[i];
arry[i] = arry[end - 1];
arry[end - 1] = temp;
return i;
}