牛客oj 習題8.1楊輝三角形(DFS)&&習題8.2全排列(DFS)

 

 

我比較笨,沒想出討論中絕大部分人的做法,不過還是把他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真的超好用。

 

 

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章