背包问题,用递归来解,简单易于理解
void print(int size, bool *flag)
{
for(int i = 0; i < size; i++) {
if(flag[i])
cout << i + 1 << " ";
}
cout << endl;
}
void Bag(int size, bool *flag, int pos, int sum)
{
if(sum < 0 || pos < 0)
return;
if(sum == 0) {
print(size, flag);
return;
}
flag[pos] = true;
Bag(size, flag, pos - 1, sum - (pos + 1));
flag[pos] = false;
Bag(size, flag, pos - 1, sum);
}
再次写此代码,立马不一样了,看着有点别扭
void printFlag(bool *flag, int size)
{
for(int i = 0; i < size; i++) {
if(flag[i])
cout << i + 1 << " ";
}
}
void printAllCombine(bool *flag, int size, int pos, int dest)
{
if(dest == 0) {
printFlag(flag, size);
cout << endl;
return;
}
if(dest < 0 || pos <= 0)
return;
flag[pos - 1] = true;
printAllCombine(flag, size, pos - 1, dest - pos);
flag[pos - 1] = false;
printAllCombine(flag, size, pos - 1, dest);
}
结果如下:
上面结果比较难看,下面改动一下代码
void printAllCombine(bool *flag, int size, int pos, int dest)
{
if(dest == 0) {
printFlag(flag, size);
cout << endl;
return;
}
if(dest < 0 || pos > size)
return;
flag[pos - 1] = true;
printAllCombine(flag, size, pos + 1, dest - pos);
flag[pos - 1] = false;
printAllCombine(flag, size, pos + 1, dest);
}
结果: