我比较笨,没想出讨论中绝大部分人的做法,不过还是把他A了。用容器模拟了DFS做出来,话说刚开始以为这题输出有问题,因为相当于杨辉三角形砍了个头。
话说讨论里那种做法也挺神奇,直接处理编号,我还以为起码要处理个数组啥的。。。
另外这题注意c++中临时变量不能作为非const的引用参数,也就是引用传参只能传一个确定参数,不能传一个或多个变量的表达式。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <cctype>
#include <cmath>
#include <climits>
using namespace std;
const int MAXN = 50005;
const int INF = INT_MAX;
vector<int> dfs(int &num){
if(num == 0){
vector<int> ans;
ans.push_back(1);
ans.push_back(1);
printf("1 1\n");
return ans;
}
num--;
vector<int> father = dfs(num);
vector<int> current;
current.push_back(1);
for(int i = 0; i < father.size()-1; i++){
int tmp = father[i] + father[i+1];
current.push_back(tmp);
}
current.push_back(1);
bool flag = false;
for(int i = 0; i < current.size(); i++){
if(flag) printf(" ");
flag = true;
printf("%d", current[i]);
}
printf("\n");
return current;
}
int main(){
// freopen("in.txt", "r", stdin);
int n;
while(~scanf("%d", &n)){
n -= 2;
vector<int> answer = dfs(n);
}
return 0;
}
这题也是递归基础题,每次从已有串中选出一个字符后再对剩余字符进行全排列,和上题的不同之处是上一题的num所在dfs没有for分支,故不用恢复num值,本题就需要回复一下。
另外这题题中说了给定的字符串中的字母已经按照从小到大的顺序排列,结果样例中出来没有排好的,所以多了一步string.sort(),stl真的超好用。
扫描二维码关注公众号,回复:
10728395 查看本文章
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <cctype>
#include <cmath>
#include <climits>
using namespace std;
const int MAXN = 10;
const int INF = INT_MAX;
bool visit[MAXN];
string str;
int len;
void dfs(int &num, string current){
if(num == 1){
for(int i = 0; i < len; i++){
if(!visit[i]){
current += str[i];
break;
}
}
cout << current << endl;
return;
}
for(int i = 0; i < len; i++){
if(!visit[i]){
num--;
visit[i] = true;
dfs(num, current + str[i]);
visit[i] = false;
num++;
}
}
return;
}
int main(){
// freopen("in.txt", "r", stdin);
while(cin >> str){
memset(visit, false, sizeof(visit));
sort(str.begin(), str.end());
len = str.size();
int lentmp = len;
dfs(lentmp, "");
printf("\n");
}
return 0;
}