Generating all distinct partitions of a number

后端 未结 5 1916
北海茫月
北海茫月 2020-12-14 12:56

I am trying to write a C code to generate all possible partitions (into 2 or more parts) with distinct elements of a given number. The sum of all the numbers of a g

5条回答
  •  庸人自扰
    2020-12-14 13:39

    I sketched this solution (it can be beautified and optimized) that shouldn't generate duplicates:

    void partitions(int target, int curr, int* array, int idx)
    {
        if (curr + array[idx] == target)
        {
            for (int i=0; i <= idx; i++)
                cout << array[i] << " ";
            cout << endl;       
            return;
        }
        else if (curr + array[idx] > target)
        {
            return;
        }
        else
        {
            for(int i = array[idx]+1; i < target; i++)
            {
                array[idx+1] = i;
                partitions(target, curr + array[idx], array, idx+1);
            }
        }
    }
    
    int main(){
        int array[100];
        int N = 6;
        for(int i = 1; i < N; i++)
        {
            array[0] = i;
            partitions(N, 0, array, 0);
        }
    }
    

提交回复
热议问题