数组分割, 把数组分解成和相等的两部分--动态规划方法

#include "stdafx.h"
#include "stdlib.h"
#include <stack>
using namespace std;

bool isSubsetSplit(int A[], int len, int sum, stack<int> &st)
{
	
	int **X = (int **)malloc((len+1)*sizeof(int *));

	for (int idx = 0; idx <= len; idx++)
	{
		X[idx] = (int *)malloc((sum+1)*sizeof(int));
		for (int m = 0; m <=sum; m++)
		{
			X[idx][m] = 0;
		}
	}
	

	X[0][0] = 1;
	for (int i = 1; i <= sum; i++)
	{
		X[0][i] = 0; //表示0及0之前的所有数据的和为 1.2.3...sum的存在性都为0;
	}

	for (int j = 1; j <= len; j++)
	{
		X[j][0] = 1; //表示第j个及地j之前的元素的组合的和为0的存在性为1 因为第j个及地j之前的元素一个都不选结果就是0
	}

	for (int i = 1; i<= len; i++) //loop从第一个元素到最后一个元素
	{
		for (int j = 1; j<= sum; j++) //loop从1到sum
		{
			if (X[i-1][j])
				X[i][j] = 1;
			for (int k = 1; k < i; k++)
			{
				if (X[k][j])
				{
					X[i][j+A[i]] = 1;
				}
			}

		}
		X[i][A[i]] = 1;
	}



	bool found = false;
	int curSum = sum/2;
	if (X[len][curSum] == 1)
	{
		for (int i = len-1; i >= 0; i--)
		{
			if (X[i][curSum] != 1)
			{
				st.push(A[i+1]);
				curSum -= A[i+1];
			}
		}

		found = true;
	}

	for (int idx = 0; idx <= len; idx++)
	{
		free(X[idx]);
	}
	free(X);

	if (found)
		return true;

	return false;
}


int _tmain(int argc, _TCHAR* argv[])
{
	int Array[] = {0,1,7,4,6,3,9,2};

	stack<int> st;

	bool bSplit = isSubsetSplit(Array, 7, 32, st);

	return 0;
}

    原文作者:动态规划
    原文地址: https://blog.csdn.net/martin_liang/article/details/8854333
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞