2

I'm looking for all the possible combination of number and the permutation of them in a fixed size of array. For example, I have the total number of 5 the desired output will be

5 0 0 0

0 5 0 0

0 0 5 0

0 0 0 5

4 1 0 0

1 4 0 0

1 0 4 0

1 0 0 4

0 1 4 0

and so on... is this possible ?

Yusry lee
  • 45
  • 3

1 Answers1

0

Use recursion:

void find(int remain, int depth, vector<int> v) {
    if (depth == 4) {
        if (remain == 0){
            for (int i = 0 ;i < 4; i++) {
                cout << v[i];
            }
            cout<<endl;
        }
        return;
    }
    for (int i = 0; i <= remain; i++) {
        v.push_back(i);
        find(remain-i, depth+1, v);
        v.pop_back();
    }
}
pfctgeorge
  • 698
  • 3
  • 9