您的位置:首页 > 编程语言 > C语言/C++

递归打印一个数所有加和的方式

2016-07-23 16:34 218 查看
例如:

6 = 5 + 1

6 = 4 + 1 + 1

6 = 3 + 1 + 1 + 1

6 = 2 + 1 + 1 + 1 + 1

6 = 1 + 1 + 1 + 1 + 1 + 1

6 = 2 + 2 + 1 + 1

6 = 3 + 2 + 1

6 = 4 + 2

6 = 2 + 2 + 2

6 = 3 + 3

#include<iostream>
#include<stack>

using namespace std;

int number;
stack<int> store;
stack<int> backup;

//min可以保证打印过程中前面的数始终大于后面的数
void print_rec(int num, int min){
if (num == 0 || num == 1)
return;
for (int i = num-1; i >= (num + 1) / 2; i--){
if (num - i >= min){
printf("%d = ", number);
printf("%d + %d", i, num - i);
while (!store.empty()){
printf(" + %d", store.top());
backup.push(store.top());
store.pop();
}
printf("\n");
while (!backup.empty()){
store.push(backup.top());
backup.pop();
}
store.push(num - i);
print_rec(i, num - i);
store.pop();
}
}
return;
}

int main(){
cin >> number;
print_rec(number,1);

return 0;
}


测试:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 递归 算法