Find all Subsets that sum upto 10. example
int [] arr ={1,2,3,4,5,6}
Subsets are :
4,5,1
4,6
2,3,5 etc.
// 找出数组中和为10的元素的组合.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
using namespace std;
void printVec(std::vector<int> &vec)
{
int size = vec.size();
for (int idx = 0; idx < size; idx++)
{
printf("%d ", vec[idx]);
}
printf("\r\n");
}
void findSum(int *A, int len, int curSum, int defSum, std::vector<int> &vec)
{
if (curSum == defSum)
{
printVec(vec);
return;
}
if (len == 0)
return;
for (int idx = 0; idx < len; idx++)
{
if (curSum + A[idx] <= defSum)
{
vec.push_back(A[idx]);
findSum(&A[idx+1], len-idx-1, curSum+A[idx], defSum, vec);
vec.pop_back();
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] ={3,4,5,10,6,2,1};
std::vector<int> vec;
findSum(arr, sizeof(arr)/sizeof(arr[0]), 0, 10, vec);
return 0;
}