1. 程式人生 > >陣列分割, 把陣列分解成和相等的兩部分--動態規劃方法

陣列分割, 把陣列分解成和相等的兩部分--動態規劃方法

#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;
}