fork(1) download
#include <iostream>
using namespace std;

int main() {
	int n;
	cin>>n;
	int a[n];
	for(int i=0; i<n; i++){
		cin>>a[i];
	}
	int s;
	cin>>s;
	int dp[s+1]={0,};
	for(int i=0; i<n; i++){
		dp[a[i]]=1;
		for(int j=a[i]+1; j<=s; j++){
			if(dp[j-a[i]]>0 or j==a[i]){
				if(dp[j]>dp[j-a[i]]+1 or dp[j]==0)
					dp[j]=dp[j-a[i]]+1;
					
			}
		}
	}
	if(dp[s]==0){
		cout<<"No solution"<<endl;
	return 0;
	}
	while(dp[s]>0){
		for (int i=0; i<n; i++){
			if(s-a[i]>=0 and dp[s]==dp[s-a[i]]+1){
				cout<<a[i]<<" ";
				s-=a[i];
				break;
			}
		}
	}
}
Success #stdin #stdout 0s 5308KB
stdin
5
1 3 7 12 32
40
stdout
1 7 32