n个数选k个数和为x选平方和最大方案
#include<cstdio> #include<vector> using namespace std; const int maxn=20; int n,k,x,maxSumSqu=-1,A[maxn]; vector<int>temp,ans; void DFS(int index,int nowK,int sum,int sumSqu) { if(nowK==k&&sum==x) { if(sumSqu>maxSumSqu) { maxSumSqu=sumSqu; ans=temp; } return; } if(index==n||nowK>k||sum>x)return; temp.push_back(A[index]); DFS(index+1,nowK+1,sum+A[index],sumSqu+A[index]*A[index]); temp.pop_back(); DFS(index+1,nowK,sum,sumSqu); } int main() { A[0]=2;A[1]=2;A[2]=3;A[3]=4; n=4;k=2;x=6; DFS(0,0,0,0); for(int i=0;i<ans.size();i++) printf("%d ",ans[i]); printf("\n"); printf("%d",maxSumSqu); }