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 ?

8
  • you mean the total always has to be 5? Commented Sep 5, 2018 at 2:50
  • 1
    How about 6 -1 0 0? Commented Sep 5, 2018 at 2:55
  • 1
    Should 3 number combinations, like 2 2 1 0, be acounted too? Commented Sep 5, 2018 at 3:01
  • 1
    All things are possible. How much time do you have? Commented Sep 5, 2018 at 3:20
  • If you just want to count the number of combinations, you can do a DP where your DP array is defined as dp[i][j] = number of ways to sum to j using i numbers. If you want to print all the combinations, use a recursive DFS as shown in pfctgeorge's answer. Commented Sep 5, 2018 at 4:10

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

You could pass the vector by reference so you don't copy the whole thing every time you call the function.
Yeah, good advice. But since I'm not very familiar with c++, I just use a brute solution to give some hint.
This solution is inefficient. :O
Also, there is only one possibility for the last number, so you don't need to loop over that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.