题目
笔试的时候遇到这么一个问题:
6 = 1+1 +1+ 1+ 1 +1
6 = 1+ 1+ 1+ 1+ 2
6 = 1+ 1+ 1+ 3
6 = 1+ 1+ 2+ 2
6 = 1+ 1+ 4
6 = 1+ 2+ 3
6 = 1+ 5
6 = 2+ 2+ 2
6 = 2+ 4
6 = 3+ 3
6 = 6
就这样,给定一个数,打印出这种形式
分析
递归,回溯。
代码
#include<iostream>
#include<vector>
using namespace std;
void print(int n, vector<int> &re){
if(n < 0)
return;
if(n == 0){
for(auto i : re){
cout << i << " ";
}
cout << endl;
}
else{
int start = 1;
int length = re.size();
if(length != 0)
start = re.at(length - 1);
for(int i = start; i <= n; i++){
re.push_back(i);
print(n - i, re);
re.pop_back();
}
}
}
int main(){
vector<int> re;
print(6, re);
return 0;
}