Split number into sum components

后端 未结 9 2156
-上瘾入骨i
-上瘾入骨i 2021-02-12 18:07

Is there an efficient algorithm to split up a number into N subsections so that the sum of the numbers adds up to the original, with a base minimum? For example, if

9条回答
  •  爱一瞬间的悲伤
    2021-02-12 18:36

    I know there`s been a long time but i would like to add my answer to help someone here is my code using recursion

    #include 
    #include 
    
    void print(int n, int * a) {
    int i ; 
    for (i = 0; i <= n; i++) {
        printf("%d", a[i]); 
       i < n ? printf(" + ") : printf("");
    }
    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 argc, char ** argv){
    int n = 10;     
    int * a = (int * ) malloc(sizeof(int) * n); 
    integerPartition (n, a, 0); 
    return(0);
    }
    

    Here n is equal to 10 but u could make it like asking the user,declare the size of a by using the new operator !

提交回复
热议问题