Advertisement
Vladislav_Bezruk

Untitled

Nov 1st, 2021
986
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 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[3][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. int combinationSum(int n){
  54.     if(memo[2][n] != -1) return memo[2][n];
  55.  
  56.     if(n == 0){
  57.         memo[2][n] = 1;
  58.         return 1;
  59.     }
  60.     if(n < 0){
  61.        memo[2][n] = 0;
  62.        return 0;
  63.     }
  64.  
  65.     int ans = 0;
  66.     for(int i = 0; i < N; i++){
  67.         int ost = n - a[i];
  68.         ans = ans + combinationSum(ost);
  69.     }
  70.     memo[2][n] = ans;
  71.     return ans;
  72. }
  73.  
  74. int main(){
  75.     for(int i = 0; i < 3; i++){
  76.         for(int j = 0; j < 10000; j++){
  77.                 memo[i][j] = -1;
  78.         }
  79.     }
  80.  
  81.     cout << " can sum " << canSum(7) << endl;
  82.  
  83.     cout << " count how many sum " << howManySum(7) << endl;
  84.  
  85.     cout << " count combination sum " << combinationSum(7) << endl;
  86.  
  87.     return 0;
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement