Print all unique solution to split number N, given choice of 1 3 5 10
For example if n is 4
{1, 1, 1, 1}
{1, 3}
Idea: You can certainly solve the problem by using DFS, but you need to traverse all possibilities and implement it by recursion after paper-cutting. The main pruning idea is that the last number must be greater than or equal to the previous number.
-
- # Include <iostream>
-
- # Include <vector>
-
- Using namespace STD;
-
- Vector <vector <int> res;
-
- Vector <int> cur;
-
- Void getallpath (vector <int> & base, int last, int N ){
-
- If (n = 0 ){
-
- Res. push_back (cur );
-
- Return;
-
- }
-
- For (INT I = 0; I <base. Size (); I ++ ){
-
- If (base [I]> N) return;
- If (base [I] <last) continue;
-
- Cur. push_back (base [I]);
-
- Getallpath (base, base [I], n-base [I]);
-
- Cur. pop_back ();
-
- }
-
- }
-
- Int main (){
-
- Vector <int> base (4 );
-
- Base [0] = 1;
-
- Base [1] = 3;
-
- Base [2] = 5;
-
- Base [3] = 10;
-
- Getallpath (base, 0, 8 );
-
- For (INT I = 0; I <res. Size (); I ++ ){
-
- For (Int J = 0; j <res [I]. Size (); j ++ ){
-
- Cout <res [I] [J] <"\ t ";
-
- }
-
- Cout <Endl;
-
- }
-
- Return 0;
-
- }
Print all unique solution to split number n