fork download
  1. #include<bits/stdc++.h>
  2. using namespace std ;
  3. int n , k , a[500] , x[500];
  4. bool check = false ;
  5. void BackTrack(int i , int start , int sum){
  6. for(int j = start ; j <= n ; j++){
  7. x[i] = a[j];
  8. if(sum + a[j] == k){
  9. check = true ;
  10. cout << "[";
  11. for(int l = 1 ; l <= i ; l++){
  12. cout << x[l] ;
  13. if( l < i) cout << " ";
  14. }
  15. cout << "]";
  16. cout << " ";
  17. }
  18. else if(sum + a[j] < k) BackTrack(i + 1 , j + 1 , sum + a[j]);
  19. }
  20. }
  21. int main(){
  22. ios::sync_with_stdio(false);
  23. cin.tie(nullptr);
  24. cout.tie(nullptr);
  25. int test ; cin >> test ;
  26. while(test--){
  27. cin >> n >> k ;
  28. for(int i = 1 ; i <= n ; i++) cin >> a[i];
  29. sort(a + 1 , a + n + 1);
  30. BackTrack(1 , 1 , 0);
  31. if(check == false) cout << "-1" ;
  32. cout << "\n";
  33. }
  34.  
  35. }
Success #stdin #stdout 0.01s 5284KB
stdin
2
5 50
5  10 15 20  25
8  53
15  22  14  26  32  9  16  8
stdout
[5 10 15 20] [5 20 25] [10 15 25] 
[8 9 14 22] [8 14 15 16] [15 16 22]