最近想要好好学一下算法,但是老觉得无从下手,论坛上有童鞋推荐一个台湾的网站http://www.csie.ntnu.edu.tw
觉得很不错,这里就当是个学习日志吧。。就是代码有的地方有些小问题
1. 最常见的问题:有一个集合,1-N共N个元素,输出可能的全排列。
#include<iostream>
using namespace std;
int solution[5];
bool used[6];
void backtracking(int n) {
if(n == 5) {
for(int i = 0; i < 5; i++)
cout << solution[i] << " ";
cout << endl;
return;
}
for(int i = 1; i <= 5; i++) {
if(!used[i]) {
used[i] = true;
solution[n] = i;
backtracking(n + 1);
used[i] = false;
}
}
}
int main() {
for(int i = 1; i <= 5; i++)
used[i] = false;
backtracking(0);
return 0;
}
#include<iostream>
using namespace std;
//int solution[5];
bool used[6];
char s[5] = {'a', 'b', 'b', 'c', 'c'};
char solution[5];
void backtracking(int n) {
if(n == 5) {
for(int i = 0; i < 5; i++)
cout << solution[i];
cout<<endl;
return;
}
char last_letter = '\0';
for(int i = 0; i < 5; i++) {
if(used[i]) continue;
if(s[i] == last_letter) continue;
last_letter = s[i];
used[i] = true;
solution[n] = s[i];
backtracking(n+1);
used[i] = false;
}
}
int main() {
for(int i = 0; i < 5; i++)
used[i] = false;
backtracking(0);
return 0;
}
3.给定一个集合类似{0,1,2,3,4},求出所有的子集合
#include<iostream>
using namespace std;
int array[5] = {0, 1, 2, 3, 4};
int subset[5];
void backtracking(int i, int n) {
if(i == 5) {
for(int i = 0; i < n; i++)
cout << subset[i] << " ";
cout << endl;
return;
}
subset[n] = array[i];// choose this value into the subset
backtracking(i + 1, n + 1);
backtracking(i + 1, n);//don't choose the value and continue to backtrack
}
int main() {
backtracking(0, 0);
return 0;
}