求推荐ibm# PhotoGear - 摄影器材
w*x
1 楼
//Print All different Combinations of a Number as a Sum of Candidate Numbers
//Before start coding, several things to consider
//1. How to deal with duplicated numbers (sort them)
//2. What exactly is the successful ending condition
//3. What exactly is the failure ending condition
//4. For the container, pass by reference or by value
void _inner_print(int a[], int n, int nSum, vector& vecRes)
{
//the success ending condition is nSum == 0 and at the
//same time n == 0!! not nSum == 0 only
//consider 1, 2, -13, 13 ==> (3)
//another error logic is :
//if (nSum == 0) { print all; (no return here) }
//this logic will generate duplicated pairs
if (nSum == 0 && n == 0)
{
for (vector::iterator it = vecRes.begin();
it != vecRes.end(); it++)
cout<cout< return;
}
if (n == 0) return;
int nDup = 1;
while (nDup < n && a[nDup-1] == a[nDup])
nDup++;
//choose 0 a[0]
_inner_print(a + nDup, n - nDup, nSum, vecRes);
for (int i = 1; i <= nDup; i++)
{
vecRes.push_back(a[0]);
nSum -= a[0];
_inner_print(a + nDup, n - nDup, nSum, vecRes);
}
//for reference, below logic is required
//think in this way, all called "_inner_print"
//must restore the vecRes' status as it passed in
for (int i = 1; i <= nDup; i++)
vecRes.pop_back();
}
void PrintAllComb(int a[], int n, int nSum)
{
assert(a && n > 0);
sort(a, a+n);
vector vecRes;
_inner_print(a, n, nSum, vecRes);
}
//Before start coding, several things to consider
//1. How to deal with duplicated numbers (sort them)
//2. What exactly is the successful ending condition
//3. What exactly is the failure ending condition
//4. For the container, pass by reference or by value
void _inner_print(int a[], int n, int nSum, vector
{
//the success ending condition is nSum == 0 and at the
//same time n == 0!! not nSum == 0 only
//consider 1, 2, -13, 13 ==> (3)
//another error logic is :
//if (nSum == 0) { print all; (no return here) }
//this logic will generate duplicated pairs
if (nSum == 0 && n == 0)
{
for (vector
it != vecRes.end(); it++)
cout<cout<
}
if (n == 0) return;
int nDup = 1;
while (nDup < n && a[nDup-1] == a[nDup])
nDup++;
//choose 0 a[0]
_inner_print(a + nDup, n - nDup, nSum, vecRes);
for (int i = 1; i <= nDup; i++)
{
vecRes.push_back(a[0]);
nSum -= a[0];
_inner_print(a + nDup, n - nDup, nSum, vecRes);
}
//for reference, below logic is required
//think in this way, all called "_inner_print"
//must restore the vecRes' status as it passed in
for (int i = 1; i <= nDup; i++)
vecRes.pop_back();
}
void PrintAllComb(int a[], int n, int nSum)
{
assert(a && n > 0);
sort(a, a+n);
vector
_inner_print(a, n, nSum, vecRes);
}