陣列分割,把陣列分割成和相等的兩部分--遞迴方法

martin_liang發表於2013-04-26
// 陣列分割問題2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <list>

using namespace std;


int getSum(int A[], int len)
{
	int sum = 0;
	for (int i = 0; i<len; i++)
	{
		sum += A[i];
	}
	return sum;
}

bool foo(int A[], int len, int curSum, int defSum, int B[], int curPos)
{
	if (curSum == defSum)
	{
		return true;
	}

	if (len == 0)
		return false;

	bool bFound = false;
	for (int i = 0; i < len; i++)
	{
		if (curSum + A[i] <= defSum)
		{
			B[curPos++] = A[i];
			if (foo(&A[1], len-1, curSum+A[i], defSum, B, curPos))
			{
				bFound = true;
				break;
			}
			B[curPos] = 0;
			curPos--;
		}
	}

	return bFound;
}

bool isSubsetSum(int Arr[], int len, int sum, int B[])
{
	std::list<int> mList;
	return foo(Arr, len, 0, sum, B, 0);
}

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

	int sum = getSum(Array, sizeof(Array)/sizeof(Array[0]));

	int B[10] = {0};
	bool bSet = isSubsetSum(Array, 7, sum/2, B);

	return 0;
}

相關文章