<pre name="code" class="cpp">// 在int数组中找出和为10的所有子集.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
void print_list(std::list<int>::iterator &itr1, std::list<int>::iterator &itr2)
{
std::list<int>::iterator itr = itr1;
while (itr != itr2)
{
printf("%d ", (*itr));
++itr;
}
printf("\n");
}
void foo(int A[], int len, int remain, std::list<int> &mList)
{
if (remain == 0)
{
print_list(mList.begin(), mList.end());
return;
}
if (len == 0)
return;
for (int idx = 0; idx < len; idx++)
{
mList.push_back(A[idx]);
foo(&A[idx+1], len-idx-1, remain-A[idx], mList);
mList.pop_back();
}
}
void printSubSetSumOfN(int A[], int len, int N)
{
std::list<int> mList;
for (int idx = 0; idx < len; idx++)
{
mList.push_back(A[idx]);
foo(&A[idx+1], len-idx-1, N-A[idx], mList);
mList.pop_back();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] ={1,2,3,4,5,6};
printSubSetSumOfN(arr, sizeof(arr)/sizeof(arr[0]), 10);
return 0;
}
在int数组中找出和为10的所有子集
最新推荐文章于 2024-09-21 14:14:39 发布