题解 | 小红的数组选数
小红的数组选数
https://www.nowcoder.com/practice/44aa435e9f7a4e13bb7f0a408295299a
n<=20,那还说啥了,直接dfs;
#include <bits/stdc++.h>
using namespace std;
int n,k;
int a[22];
int ans=0;
int used[22];
void dfs(int x,int sum)
{
if(sum==k)
{
ans++;
return;
}
if(sum>k)
{
return ;
}
if(sum<k)
{
for(int i=x+1;i<=n;i++)
{
dfs(i,sum+a[i]);
}
}
return ;
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cin>>n>>k;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
sort(a+1,a+1+n);
dfs(0,0);
memset(used,-1,sizeof(used));
cout<<ans<<endl;
return 0;
}