Advertisement
Vladislav_Bezruk

Untitled

Nov 1st, 2021
1,014
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include<iostream>
  2. #define N int(sizeof(a) / sizeof(a[0]))
  3.  
  4. using namespace std;
  5.  
  6. int a[] = {5, 3, 4, 7};
  7. int memo[2][10000];
  8.  
  9. bool canSum(int n){
  10.     if(memo[0][n] != -1) return memo[0][n];
  11.  
  12.     if(n == 0) {
  13.         memo[0][n] = 1;
  14.         return true;
  15.     }
  16.     if(n < 0) {
  17.         memo[0][n] = 0;
  18.         return false;
  19.     }
  20.  
  21.     for(int i = 0; i < N; i++){
  22.         int ost = n - a[i];
  23.         bool res = canSum(ost);
  24.         if(res == true){
  25.             memo[0][n] = 1;
  26.             return true;
  27.         }
  28.     }
  29.     memo[0][n] = 0;
  30.     return false;
  31. }
  32.  
  33. int howManySum(int n){
  34.     if(memo[1][n] != -1) return memo[1][n];
  35.  
  36.     if(n == 0){
  37.         memo[1][n] = 1;
  38.         return 1;
  39.     }
  40.     if(n < 0){
  41.        memo[1][n] = 0;
  42.        return 0;
  43.     }
  44.     int ans = 0;
  45.     for(int i = 0; i < N; i++){
  46.         int ost = n - a[i];
  47.         ans = ans + howManySum(ost);
  48.     }
  49.     memo[1][n] = ans;
  50.     return ans;
  51. }
  52.  
  53. void combinationSum(int n, string s){
  54.     if(n == 0){
  55.         cout << "combination = " << s << endl;
  56.         return;
  57.     }
  58.     if(n < 0){
  59.        return;
  60.     }
  61.  
  62.  
  63.     for(int i = 0; i < N; i++){
  64.         int ost = n - a[i];
  65.         char num[2] = {a[i] + '0', '\0'};
  66.         string ns = s + num + " ";
  67.         combinationSum(ost, ns);
  68.     }
  69. }
  70.  
  71. int main(){
  72.     for(int i = 0; i < 2; i++){
  73.         for(int j = 0; j < 10000; j++){
  74.                 memo[i][j] = -1;
  75.         }
  76.     }
  77.  
  78.     cout << "can sum " << canSum(7) << endl;
  79.  
  80.     cout << "count how many sum " << howManySum(7) << endl;
  81.  
  82.     combinationSum(7, "");
  83.  
  84.     return 0;
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement