Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <conio.h>
- using namespace std;
- int n, k, s, x[101];
- void initializare(int k)
- {
- if(k == 1) x[k]=0;
- else x[k] = x[k - 1] - 1;
- }
- int solutie()
- {
- if(s == n) return 1;
- return 0;
- }
- int valid(int k)
- {
- if(s + x[k] <= n)
- {
- s = s + x[k];
- return 1;
- }
- return 0;
- }
- void afisare(int k)
- {
- for(int i = 1;i < k;i++)
- cout << x[i] << " + ";
- cout << x[k] << " = " << n;
- cout << endl;
- s = s - x[k];
- }
- void backTracking()
- {
- k = 1;
- initializare(k);
- while(k > 0)
- {
- if(x[k] < n - s)
- {
- x[k]++;
- if(valid(k))
- if(solutie())
- afisare(k);
- else
- {
- k++;
- initializare(k);
- }
- }
- else
- {
- k--;
- s = s - x[k];
- }
- }
- }
- int main()
- {
- cout << "Dati un numar: ";
- cin >> n;
- cout << endl << "Numarul poate fi descompus ca urmatoarele sume de numere: " << endl;
- backTracking();
- return 0;
- _getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement