【IT面试题003】将一个正整数写成若干个整数之和

将一个正整数写成若干个整数之和,打印出所有的可能,每种和输出时,加数升序排列

#include <iostream>

#include <string>
#include <vector>
using namespace std;


vector<int> solution;
int gNum; //目前的加数个数
int gCurSum; //当前和
int gN; //目标和
int gSolCount;
void PrintSolution()
{
	for (int i = 0;i < gNum;i++)
	{
		cout << solution[i] << " ";
	}
	cout << endl;
}
void Go()
{
	if (gCurSum == gN)
	{
		gSolCount ++;
		PrintSolution();
		return;
	}
	int lastAdd = 1; // 从1开始
	if (gNum > 0)
	{
		lastAdd = solution[gNum - 1];
	}
	if (lastAdd > (gN - gCurSum))  //如果最小的可行加数都大于剩余和,就不要继续了
	{
		return;
	}
	for (int adder = lastAdd;adder <= (gN - gCurSum); adder++)
	{
		gCurSum += adder;
		gNum ++;
		if (solution.size() >= gNum)
		{
			solution[gNum - 1] = adder;
		}else{
			solution.push_back(adder);
		}
		Go();
		//回溯
		gCurSum -= adder; 
		gNum --;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{

	gN = 10;
	gSolCount = 0;
	gCurSum = gNum = 0;
	Go();
	cout << gSolCount << endl;
}

posted on 2011-06-04 17:57  speedmancs  阅读(332)  评论(0编辑  收藏  举报

导航