How do I generate integer partitions?

前端 未结 7 1568
悲哀的现实
悲哀的现实 2021-01-20 04:54

I have a list of numbers like 1,2,3 and I want to find all the combination patterns that sum up to a particular number like 5. For example:

Sum=5
Numbers:1,2         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-20 05:21

    You can use following code .. it wiil give you a exact answer as you want..

    void print(int n, int * a)
    
    {
       int i ; 
    
       for (i = 0; i <= n; i++) 
    
       {
    
      printf("%d", a[i]); 
    
      }
    
     printf("\n"); 
    
    }
    
    
    void integerPartition(int n, int * a, int level)
    
    {
    
       int first; 
    
      int i; 
    
      if (n < 1) 
    
     return ;    
    
     a[level] = n;
    
      print(level, a);
    
      first = (level == 0) ? 1 : a[level-1];
    
      for(i = first; i <= n / 2; i++)
    
       {
    
           a[level] = i; 
    
           integerPartition(n - i, a, level + 1);
    
       }
    
    }
    
    int main()
    
      {
    
       int n = 10;     
    
       int * a = (int * ) malloc(sizeof(int) * n); 
    
       integerPartition (n, a, 0); 
    
       return(0);
    
    }
    

提交回复
热议问题