一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值。

比如{3,2,4,3,6} 可以分成

  • {3,2,4,3,6} m=1;
  • {3,6}{2,4,3} m=2
  • {3,3}{2,4}{6} m=3

所以m的最大值为3。

bool isShare(int* a, int* group, int len, int m, int groupSize, int groupId,
		int curSize) {
	if (curSize == 0) {
		groupId++;
		curSize = groupSize;
		if (groupId == m + 1) {
			return 1;
		}

	}
	for (int i = 0; i < len; ++i) {
		if (group[i]) {
			continue;
		}
		group[i] = groupId;
		if (isShare(a, group, len, m, groupSize, groupId, curSize - a[i])) {
			return 1;
		}
		group[i] = 0;
	}
	return 0;
}

int maxShare(int* a, int len) {
	int sum = getArraySum(a, len);
	int* group = new int[len];

	for (int m = len; m >= 2; --m) {
		if (sum % m) {
			continue;
		}
		memset(group, 0, len * sizeof(int));
		if (isShare(a, group, len, m, sum / m, 1, sum / m)) {
			//打印分组情况
			cout << "分组情况:" << endl;
			for (int i = 1; i <= m; ++i) {
				for (int j = 0; j < len; j++) {
					if (i == group[j]) {
						cout << a[j] << " ";
					}
				}
				cout << endl;
			}

			return m;
		}
	}
	return 1;
}


你可能感兴趣的:(算法-数组)