#include <iostream>
using namespace std;
template <typename T>
class Stack{
private:
class Element{
public:
T value;
Element(T v){
value = v;
next = NULL;
}
Element* next;
};
Element* top;
public:
Stack(){
top = NULL;
}
T getTop(){
return top->value;
}
void push(T v){
Element* e = new Element(v);
if(!top) {
top = e;
} else {
e->next = top;
top = e;
}
}
T pop(){
if(!top)
return NULL;
T v = getTop();
Element* temp = top;
top = top -> next;
delete temp;
return v;
}
bool isEmpty(){
return top == NULL;
}
void printStack(){
Element* cur = top;
while(cur) {
cout<<cur->value<<" ";
cur = cur->next;
}
}
};
Stack<int> stack;
void search(int m,int cur,int n) {
if(cur > n)
return;
if(cur == m){
stack.push(cur);
stack.printStack();
stack.pop();
cout<<endl;
return;
}
if(cur > m )
return;
stack.push(cur);
search(m-cur,cur+1,n);
stack.pop();
search(m,cur+1,n);
}
int main(){
search(15,1,9);
}
输入两个整数n和m,从数列1,2,3.......n 中随意取几个数, 使其和等于m,要求将其中所有的可能组合列出来。
最新推荐文章于 2020-03-09 03:12:58 发布