一、时间复杂度为O(2^n)
void DFS(int index, int sumW, int sumC){ if (index == n){ if(sumW <= V && sumC > maxvalue){ maxvalue = sumC; } return; } DFS(index+1,sumW,sumC); DFS(index+1,sumW+w[index],sumC+c[index]); }
二、“剪枝”
void DFS(int index, int sumW, int sumC){ if (index == n){ return; } DFS(index+1,sumW,sumC); if(sumW + w[index] <= V){ //只有当下一个物品的重量不超标才进行选择 if (sumC+ c[index] > maxvalue){ maxvalue = sumC + c[index]; } DFS(index+1,sumW+w[index], sumC+c[index]); } }
int main(){ cin >> n >> V; for (int i = 0; i < n; i++) cin >> w[i]; for (int i = 0; i < n; i++) cin >> c[i]; DFS(0,0,0); cout << maxvalue; return 0; }