图的邻接表存储
图的邻接表存储:对图的每个顶点建立一个单链表。需要两种类型的节点。一种是表头节点(数量=图的顶点数),以向量形式存储,以便随机访问任一顶点的链表;一种是与表头节点表示的顶点邻接的顶点,链接到相应表头节点后面。与表头节点表示的顶点邻接的顶点的节点,包括一个顶点的数据域adjvex和一个指向下一个与表头节点邻接的顶点的指针。
const int MAX_VERTEX_NUM = 20;
//图的邻接表存储:对图的每个顶点建立一个单链表。需要两种类型的节点。一种是表头节点(数量=图的顶点数),以向量形式存储,以便随机访问任一顶点的链表;
//一种是与表头节点表示的顶点邻接的顶点,链接到相应表头节点后面
//与表头节点表示的顶点邻接的顶点的节点,包括一个顶点的数据域adjvex和一个指向下一个与表头节点邻接的顶点的指针
typedef struct adjNode{
int adjvex;
struct adjNode *nextadj;
}adjNode;
//表头节点,包括顶点的数据域和指向第一个与其邻接的顶点的指针
typedef struct VNode {
int data;
adjNode *firstadj;
}VNode,adjList[MAX_VERTEX_NUM]; //结构体数组存储所有表头结点
//图
typedef struct {
adjList vertices; //表头节点数组
int vexnum, arcnum; //图的顶点数和边数
}Graph;
//建立有向图
void BuildAdjlist(Graph& G,int n,int e) {
G.vexnum = n;
G.arcnum = e;
//先逐个画出图的全部顶点 从0到n编号
for (int i = 0; i < n; ++i) {
G.vertices[i].data = i;
G.vertices[i].firstadj = NULL;
}
for (int i = 0; i < e; ++i) {
cout << "输入有向边:";
int u, v;
cin >> u >> v;
//表头节点u的邻接表中应加一个顶点v,即插入一个顶点p(插到最前面)
adjNode *p = new adjNode;
p->adjvex = v;
p->nextadj = G.vertices[u].firstadj;
G.vertices[u].firstadj = p;
//delete p; // 不可delete p!!正在构造链表
}
}
//建立无向图
void BuildAdjlist(Graph& G,int n,int e) {
G.vexnum = n;
G.arcnum = e;
//先逐个画出图的全部顶点 从0到n编号
for (int i = 0; i < n; ++i) {
G.vertices[i].data = i;
G.vertices[i].firstadj = NULL;
}
for (int i = 0; i < e; ++i) {
cout << "输入无向边:";
int u, v;
cin >> u >> v;
//表头节点u的邻接表中应加一个顶点v,即插入一个顶点p(插到最前面)
adjNode *p = new adjNode;
p->adjvex = v;
p->nextadj = G.vertices[u].firstadj;
G.vertices[u].firstadj = p;
adjNode* q = new adjNode;
q->adjvex = u;
q->nextadj = G.vertices[v].firstadj;
G.vertices[v].firstadj = q;
//delete p; // 不可delete p!!正在构造链表
}
}
//深搜,从第v个顶点开始遍历
void dfs(Graph &G,int v,vector<bool>& visit){
visit[v] = true;
//visit
cout<<G.vertices[v].data<<" ";
adjNode *p = G.vertices[v].firstadj;
while(p!=NULL){
if(visit[p->adjvex]==0){
dfs(G,p->adjvex,visit);
}
p = p->nextadj;
}
}
int main() {
Graph G;
int n, e;
cout<< "输入顶点数和边数:";
cin >> n >> e;
BuildAdjlist(G, n, e);//0 1 0 3 1 2 2 1 2 5 3 2 3 5 4 3 5 4 5 1
//打印
for (int i = 0; i < n; ++i){
cout << G.vertices[i].data;
if (G.vertices[i].firstadj == NULL) {
cout << endl;
continue;
}
adjNode* p = G.vertices[i].firstadj;
while (p != NULL) {
cout << "->" << p->adjvex;
p = p->nextadj;
}
cout << endl;
}
//深搜遍历
vector<bool> visit(n,false);
dfs(G,0,visit);
}
简单的二维数组模拟邻接表:
图的遍历
从图的某一顶点出发访问图中其余顶点,且使每一个顶点仅被访问一次。为了避免同一顶点被访问多次,在遍历过程中必须记下每个已访问过的顶点,所以需设一个辅助数组visited[1...n ]
。
深度优先搜索和广度优先搜索对有向图和无向图都适用。
深度优先搜索类似于树的先根遍历,是树的先根遍历的推广。广度优先搜索类似于树的按层次遍历的过程,需附设队列以存储已被访问的路径长度为1,2,…的顶点。
struct GraphNode {
int label;
vector<GraphNode*> neighbors;
GraphNode(int x) : label(x) {};
};
//深度优先搜索(基于邻接表)
void DFS_Graph(GraphNode* node, int visit[]) { //数组作参数传给函数时,传的是指针
visit[node->label] = 1;
printf("%d", node->label);
for (int i = 0; i < node->neighbors.size(); ++i) {
if (visit[node->neighbors[i]->label] == 0) {
DFS_Graph(node->neighbors[i], visit);
}
}
}
//广度优先搜索
void BFS_Graph(GraphNode* node, int visit[]) {
queue<GraphNode*> Q;
Q.push(node);
visit[node->label] = 1;
while(!Q.empty()) {
GraphNode* node = Q.front();
Q.pop();
printf("%d", node->label);
for (int i = 0; i < node->neighbors.size(); ++i) {
if (visit[node->neighbors[i]->label] == 0) {
Q.push(node->neighbors[i]);
visit[node->neighbors[i]->label] = 1;
}
}
}
}
int main() {
const int n = 5;
vector<GraphNode*> Graph(n); //顶点
//GraphNode* Graph[n];
//为每个顶点申请空间,值为顶点编号
for (int i = 0; i < n; i++) {
Graph[i] = new GraphNode(i);
}
//添加边
Graph[0]->neighbors.push_back(Graph[2]);
Graph[0]->neighbors.push_back(Graph[4]);
Graph[1]->neighbors.push_back(Graph[0]);
Graph[1]->neighbors.push_back(Graph[2]);
Graph[2]->neighbors.push_back(Graph[3]);
Graph[3]->neighbors.push_back(Graph[4]);
Graph[4]->neighbors.push_back(Graph[3]);
int visit[n] = { 0 }; //标记已访问的顶点
for (int i = 0; i < n; i++) {
if (visit[i] == 0) { //顶点没有标记才访问
printf("from label (%d):", Graph[i]->label);
DFS_Graph(Graph[i], visit);
cout << endl;
}
}
for (int i = 0; i < n; ++i) {
delete Graph[i];
}
return 0;
}
个人总结:
深度优先搜索和广度优先搜索不仅是遍历图的算法,更广泛的理解是一种算法思想,可以用于解决各种搜索问题。
深搜的基本思想:从当前未被访问的一个节点出发,访问此节点(实际问题中可能是对该节点进行某些条件判断或某种操作),然后依次从此节点的未被访问的邻接点出发深度优先搜索,直到问题规模中所有满足条件的节点都被访问到。
基于这种思想,很多问题都可以在此基础上扩展并解决。
例1:
https://leetcode-cn.com/problems/island-perimeter/
思路:对陆地格子进行深度优先搜索,直到所有陆地格子都被访问到。
class Solution {
constexpr static int dx[4] = { 0,1,0,-1 };
constexpr static int dy[4] = { 1,0,-1,0 };
public:
int dfs(int x,int y, vector<vector<int>>& grid,int row,int col) {
if (x<0 || x>=row || y<0 || y>=col || grid[x][y] == 0) {
return 1; //这些情况都需要周长加1
}
if (grid[x][y] == 2) { //此格子已经访问过
return 0;
}
grid[x][y] = 2; //表示已被访问过
int ans = 0;
for (int i = 0; i < 4; ++i) {
int xx = x + dx[i];
int yy = y + dy[i];
ans += dfs(xx, yy, grid, row, col);
}
return ans;
}
int islandPerimeter(vector<vector<int>>& grid) {
int row = grid.size(), col = grid[0].size();
int res = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] == 1) { //对陆地格子深搜
res += dfs(i,j,grid,row,col);
}
}
}
return res;
}
};
例2:
https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/
更广泛的深搜思想是利用递归回溯的思想,对于解决一些需要不断尝试并回溯的问题很有效。不过有时候暴力深搜会导致超时,所以需要在深搜过程中加入记忆化搜索来减少重复工作。
深度优先算法在计算时,只会考虑这个问题是否有解,并不会考虑这个这个解是否是最优解(即遍历出最短路径),而广度优先算法则可以获得问题的最优解(最短路径),但是在遍历时会保存一些数据信息,如果嵌套太深,那么就会占用较大内存,所以在选择算法时,需要根据实际问题来进行选择,而不能一概而论
例3:
https://leetcode-cn.com/problems/word-break/
题解
//1.动态规划
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
//动态规划:dp[i]表示字符串中前i个字符s[0...i-1]是否可以被拆分成若干个字典中的单词
//状态转移方程:i每次加1,都要判断新的子串s[0...i-1]中是否可以找到一个分割点j,使得j前面的子串s[0...j-1]和j后面的子串s[j...i-1]都合法,
//(即s[0...j-1]中可包含若干个字典中的单词,s[j...i-1]是一个在字典中的单词),若找到满足条件的j点,则说明dp[i]=true
//dp[i] = dp[j] && s.substr(j,i-j)∈wordDict
//初始dp[0]=true, 若前i个字符是字典中的一个单词,则j=0
unordered_set<string> st;
for (auto& word : wordDict) {
st.insert(word);
}
vector<bool> dp(s.size() + 1);
dp[0] = 1;
for (int i = 1; i <= s.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && st.find(s.substr(j, i - j)) != st.end()) {
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};
//2.dfs
class Solution {
public:
/*深搜:"leetcode"能否break(被拆分成若干个字典中的单词),可以拆分为:"l"是否是字典中的单词、剩余子串能否break,"le"是否为字典中的单词、
剩余子串能否break,......。
用dfs递归回溯,考察所有的拆分可能,指针i从左往右扫描当前字符串s(i把当前字符串划分为两部分):(记忆化搜索)
1.如果指针左边子串在字典中,则递归考察右侧剩余子串能否break,能则返回true且记录当前dfs的字符串首字符位置vis[pos]=1
2.如果指针左侧子串不在字典中,则回溯,考察别的分支
*/
int len;
bool dfs(string& s, int pos, unordered_set<string>& st,vector<int>& vis) {
if (pos == len) { //pos==len表示字符串s能够break
return true;
}
if (vis[pos] != -1) { //表示已访问过该节点,即以pos开始的子串。
return vis[pos];
}
for (int i = pos; i < len; ++i) {
if (st.find(s.substr(pos, i - pos + 1)) != st.end()) {
if (dfs(s, i + 1, st, vis)) {
vis[pos] = 1; //以pos开始的子串中有字典中的单词
return true;
}
// else vis[pos] = 0;
}
}
vis[pos] = 0; //表示从pos开始的子串中没有在字典中的单词
return false;
}
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> st;
for (auto& x : wordDict) {
st.insert(x);
}
len = s.size();
vector<int> vis(len, -1);
return dfs(s, 0, st, vis);
}
};
//3.bfs
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> st;
for (auto& x : wordDict) {
st.insert(x);
}
int len = s.size();
vector<int> vis(len, 0);
queue<int> Q;
Q.push(0);
while (!Q.empty()) {
int pos = Q.front();
Q.pop();
if (vis[pos]) continue;
vis[pos] = 1;
for (int i = pos + 1; i <= len; ++i) {
if (st.find(s.substr(pos, i - pos)) != st.end()) {
if (i < len) {
Q.push(i);
}
else { //i==len 此时前缀已包含到整个字符串,是一个单词
return true;
}
}
}
}
return fasle;
}
};
int main() {
string s = "catsand";
vector<string>dic({ "cat","cats","and" });
Solution ss;
cout<<ss.wordBreak(s, dic);
}
例3
https://vjudge.net/problem/POJ-1426
题意:给出n(1<=n<=200),求出全部由01组成的能整除n的正整数。
**思路:**由于结果只能含0或1,所以从1开始深搜(最高位为1),之后每一位可以是0或1,故搜索有两个方向:ans10 或 ans10+1 .
dfs终止条件:找到答案(能整除n)或者当前数的长度大于19(long long最大值就是19位)。
#include <iostream>
using namespace std;
typedef long long ll;
int n;
bool dfs(ll ans, int idx) {
if (idx > 19) {
return false;
}
if (ans % n == 0) {
cout << ans;
return true;
}
if (dfs(ans * 10, idx + 1)) {
return true;
}
if (dfs(ans * 10 + 1, idx + 1)) {
return true;
}
return false;
}
int main() {
while (cin >> n && n) {
dfs(1, 1);
}
return 0;
}
例4
题意:
给定一个ab的矩形,给定一个hw的初始矩形,给定一n个元素的操作数组a(2 <= a[i] <= 1e5),要求每次从数组中选一个数a[i],让被操作的矩形(初始时是hw的矩形)的长或者宽乘以a[i],每个数不能被多次选择,求最小的操作数使得初始矩形的长和宽足以容纳ab的矩形,无论怎么选择都不能满足条件则输出-1(a,b,h,w,n <= 1e5)。
题解:
直接dfs搜索即可,具体地,先将a数组从大到小进行排序,数字大的优先被选择,因为如果都选择小的那么操作数肯定会增加,所以不会在大的数没被选择时就去选择小数,排序后依次搜索就行,不过这时得考虑上界,因为a[i] >= 2,又2 ^ 17 >= 1e5,所以最多只考虑前34个数就行(即就算前34个数全是2,则两个2 ^ 17足以表示a[i]所能表示的两个最大数 ),对于每个数,只考虑把它乘在h或者w上就行(调用dfs时调用两次),搜索时动态更新答案,若答案从未更新则输出-1。接下来考虑剪枝,主要分为以下三类:
1.h和w都同时大于a和b,更新答案
2.当前已使用的操作数已大于目前搜到的最小答案
3.n个元素已经使用完
#include<iostream>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
int n, ans;
LL a, b, h, w, c[maxn];
bool cmp(LL x, LL y) {
return x > y;
}
//void dfs(LL x, LL y, int k, int num) {
// if (x >= a && y >= b) {
// ans = min(ans, num);
// return;
// }
// if (num >= ans || k > n || k > 34) {
// return;
// }
// if (x < a) {
// dfs(x * c[k], y, k + 1, num + 1);
// }
// if (y < b) {
// dfs(x, y * c[k], k + 1, num + 1);
// }
//}
bool dfs(LL x, LL y, int idx, int num) {
if (x >= a && y >= b) {
ans = min(ans,num);
return true;
}
if (num >= ans || idx > n || idx > 34) {
return false;
}
if (x < a && dfs(x * c[idx], y, idx + 1, num + 1)) {
return true;
}
if (y < b && dfs(x, y * c[idx], idx + 1, num + 1)) {
return true;
}
return false;
}
int main() {
scanf_s("%lld%lld%lld%lld%d", &a, &b, &h, &w, &n);
for (int i = 1; i <= n; ++i) {
scanf_s("%lld", &c[i]);
}
ans = inf;
sort(c + 1, c + n + 1, cmp);
dfs(h, w, 1, 0);
dfs(w, h, 1, 0);
if (ans == inf)
printf("-1\n");
else
printf("%d\n", ans);
return 0;
}
例5
问题描述:
给定整数a1,a2, … an,判断能否从中选出若干个数,使得它们的和为k。
限制条件:
1<=n<=20
-10^8<=ai<=10 ^8 (int即可)
-10^8<=k<=10 ^8
思路:暴力深搜,从a0开始依次判断,决定ai加入或不加入,对每一个种组合进行判断,决定是否存在和为k的情况。
时间复杂度:O(2^n)。 注意到这是个很大的复杂度,但题目中限制条件 n<=20 ,2 ^20 换算一下为16 ^5, 最大不超过10 ^6,因此可行。
vector<int> a ( { 1,2,4,7 } );
int target = 7;
bool flag = false;
vector<bool> vis(a.size(), false);
vector<int> path; //存储和为目标数的所有元素
void dfs(int sum, int idx) {
if (sum == target) {
flag = true;
for (auto& x : path) {
cout << x << ends;
}
cout << endl;
return;
}
if (sum > target || idx >= a.size()) {
return;
}
//每个元素可以有加或不加两种选择,对每种组合进行深搜
/*dfs(sum, idx + 1);
dfs(sum + a[idx], idx + 1); //不用vis数组*/
if (vis[idx] == false) {
vis[idx] = true;
dfs(sum, idx + 1);
path.push_back(a[idx]); //在选择加a[idx]之前把它添加到数组path, 完成之后弹出
dfs(sum + a[idx], idx + 1);
path.pop_back();
vis[idx] = false;
}
}
//bool dfs(int idx,int sum) {
// if (sum == target) {
// return true;
// }
// if (idx >= 4 || sum > target) {
// return false;
// }
// //if (idx >= 4) return sum == target;
// //每个元素可以有加或不加两种选择,对每种组合进行深搜判断
// if (dfs(idx + 1, sum)) {
// return true;
// }
// if (dfs(idx + 1, sum + a[idx])) {
// return true;
// }
// return false;
//}
int main() {
/*if (dfs(0, 0)) {
cout << "yes" << endl;
}*/
//vector<int> res;
dfs(0, 0);
if (flag) {
cout << "yes" << endl;
}
else {
cout << "no";
}
}
例6
思路:先放当前位置,然后深搜放置下一个位置。
vector<int> a(7); //6个位置
vector<bool> used(10, false); //1~9是否被使用
//递归深搜放置每一个位置
void dfs(int pos) {
if (pos > 6) {
int x = a[1] * 10 + a[2];
int y = a[3] * 10 + a[4];
int z = a[5] * 10 + a[6];
if (x - y == z) {
cout << x << "-" << y << "=" << z << endl;
}
return;
}
for (int i = 1; i < 10; ++i) {
if (used[i] == false) {
used[i] = true;
a[pos] = i;
dfs(pos + 1); //深搜,依次放置每个位置
used[i] = false; //放置完后仍未满足条件,则将深搜到的位置取出,再放置其它数字,所有数字尝试完后回退到上一个位置继续深搜
}
}
return;
}
int main() {
dfs(1);
return 0;
}
例7
n的全排列
//n的全排列 用path数组记录每种结果
int cnt = 0;
int n;
void dfs(int n, int pos, vector<bool>& vis,vector<int>& path) {
if (pos > n) {
cnt++;
for (int i = 1; i <= n; ++i) {
cout << path[i] << ends;
}
cout << endl;
return;
}
for (int i = 1; i <= n; ++i) {
if (vis[i] == false) {
vis[i] = true;
path[pos] = i;
dfs(n, pos + 1,vis, path);
vis[i] = false;
}
}
return;
}
int main()
{
cin >> n;
vector<bool> vis(n + 1, false);
vector<int> path(n + 1);
dfs(n, 1,vis,path);
cout << cnt << endl;
}
例8
迷宫问题
深度优先搜索:
int x, y, ex, ey;
int m[5][6] = { {1,0,0,1,0,1},{1,1,1,1,1,1},{0,0,1,1,1,0},{1,1,1,1,1,0},{1,1,1,0,1,1} };
int dx[4] = { -1,0,1,0 }; //左上右下
int dy[4] = { 0,1,0,-1 };
vector<vector<bool>> vis(5, vector<bool>(6, false));
vector<pair<int,int>> path;
int min_step = INT_MAX; //最小步数
void dfs(int x,int y,int step) {
if (x == ex && y == ey) {
cout << step << ends;
min_step = min(step, min_step);
for (auto& x : path) {
cout << "(" << x.first << "," << x.second << ")" << ends;
}
cout << endl;
return;
}
if (x < 0 || x>=5 || y < 0 || y>=6) {
return;
}
for (int i = 0; i < 4; ++i) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && xx < 5 && yy >= 0 && yy < 6 && m[xx][yy] == 1 && vis[xx][yy] == false) {
vis[xx][yy] = true;
path.push_back(make_pair(xx,yy));
dfs(xx, yy, step + 1);
path.pop_back();
vis[xx][yy] = false;
}
}
}
int main() {
cin >> x >> y >> ex >> ey; //00 45
vis[x][y] = true;
path.push_back(make_pair(x, y));
dfs(x, y, 0);
cout << min_step;
}
广度优先搜索(只求解最短路径):
struct node {
node *pre;
int x;
int y;
int step; //入口到当前点的步数
node(){}
node(node *p,int xx, int yy, int s) : pre(p), x(xx), y(yy), step(s) {}
};
int x, y, ex, ey;
int m[5][6] = { {1,0,0,1,0,1},{1,1,1,1,1,1},{0,0,1,1,1,0},{1,1,1,1,1,0},{1,1,1,0,1,1} };
int dx[4] = { -1,0,1,0 }; //左上右下
int dy[4] = { 0,1,0,-1 };
queue<node> Q;
vector<vector<bool>> vis(5, vector<bool>(6, false));
vector<pair<int,int>> path;
//递归打印最短路径
void print(node* cur) {
if (cur->pre != NULL) {
print(cur->pre);
}
cout << "(" << cur->x << "," << cur->y << ")" << ends;
}
void bfs(int x,int y,int ex,int ey) {
vis[x][y] = true;
Q.push(node(NULL, x, y, 0));
while (!Q.empty()) {
node *tmp = new node(Q.front());
Q.pop();
for (int i = 0; i < 4; ++i) {
int xx = tmp->x + dx[i];
int yy = tmp->y + dy[i];
if (xx >= 0 && xx < 5 && yy >= 0 && yy < 6 && m[xx][yy] == 1 && vis[xx][yy] == false) {
if (xx == ex && yy == ey) {
cout << tmp->step + 1;
print(tmp);
cout << "(" << xx << "," << yy << ")";
exit(0);
}
vis[xx][yy] = true;
Q.push(node(tmp, xx, yy, tmp->step + 1));
}
}
}
}
int main() {
cin >> x >> y >> ex >> ey; //00 45
bfs(x, y, ex, ey);
}
例9
类似0-1背包问题
//10个州,state[i][0]表示该州可获得票数,state[i][1]表示需要时间
int state[10][2] = { {38,3},{29,2},{20,1},{20,1},{18,1},{16,1},{16,1},{15,1},{29,2},{55,5} };
int len = sizeof(state) / (2*sizeof(int));
int day = 10;
int votes = 0;
vector<vector<int>> mem(11, vector<int>(11,0)); //记忆化搜索 指定索引后的州中,剩余时间内,能获得的最多票数
//vector<int> path;
void dfs(int pos,int time,int votenum) {
if (pos >= len || time <= 0) {
votes = max(votes, votenum);
/*if (time == 0) { //深搜难以得到最优解路径
for (auto& x : path) {
cout << x << ends;
}
cout << endl;
}*/
return;
}
if (mem[pos][time] != 0) { //若记忆表中存在历史结果,直接使用
votenum = mem[pos][time];
return;
}
//每个州可选择去或不去
dfs(pos + 1, time, votenum);
//path.push_back(pos);
if (time >= state[pos][1]) { //剩余时间足够才能去
//path.push_back(pos); //这样得到的是所有解路径
dfs(pos + 1, time - state[pos][1], votenum + state[pos][0]);
//path.pop_back();
}
mem[pos][time] = max(votes, votenum);
return;
}
//动态规划
int states[11][2] = { {0,0}, {38,3},{29,2},{20,1},{20,1},{18,1},{16,1},{16,1},{15,1},{29,2},{55,5} };
vector<vector<int>> dp(len + 1, vector<int>(day + 1, 0));
vector<int> paths(11);
void findpath(int i,int j) { //回溯找最佳解路径
if (i > 0) {
if (dp[i][j] == dp[i - 1][j]) {
paths[i] = 0;
findpath(i - 1, j);
}
else if (j >= states[i][1] && dp[i][j] == dp[i - 1][j - states[i][1]] + states[i][0]) {
paths[i] = 1;
findpath(i - 1, j - states[i][1]);
}
}
}
//上面的递归深搜是自顶向下思考:在去与不去两种方案中选择。
//动态规划 自下向上 (参考0-1背包问题):先解决一个州,只有一天时间,能获得的最大票数
int dp_solution() {
//dp[i][j] : 前i个州,在j天时间内,能得到的最大票数
//vector<vector<int>> dp(len + 1, vector<int>(day + 1, 0));
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= day; ++j) {
if (states[i][1] > j) {
dp[i][j] = dp[i - 1][j];
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - states[i][1]] + states[i][0]);
}
}
}
return dp[10][10];
}
int main() {
//dfs(0, day, 0);
//cout << votes;
cout << dp_solution() << endl;
findpath(10, 10);
for (int i = 0; i < 11; ++i) {
if (paths[i] == 1) {
cout << i << ends;
}
}
}
例10:子集2
(在深搜过程中保存所有子集)
class Solution {
public:
vector<vector<int>> ans;
vector<int> cur;
// vector<int> v;
//深搜:每个元素都有选和不选两种选择
void dfs(int idx,vector<int>& nums) {
//存深搜过程中的所有子集
ans.push_back(cur);
if(idx == nums.size()) {
return;
}
for(int i=idx; i<nums.size(); ++i) {
if(i > idx && nums[i] == nums[i-1]) continue; //去重
//选
cur.push_back(nums[i]);
dfs(i+1,nums);
//不选
cur.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
// v = nums;
dfs(0,nums);
return ans;
}
};
class Solution {
public:
vector<int> t;
vector<vector<int>> ans;
void dfs(bool choosePre, int cur, vector<int> &nums) {
if (cur == nums.size()) {
ans.push_back(t);
return;
}
//不选
dfs(false, cur + 1, nums);
//去重
if (!choosePre && cur > 0 && nums[cur - 1] == nums[cur]) {
return;
}
//选
t.push_back(nums[cur]);
dfs(true, cur + 1, nums);
t.pop_back();
}
vector<vector<int>> subsetsWithDup(vector<int> &nums) {
sort(nums.begin(), nums.end());
dfs(false, 0, nums);
return ans;
}