使用DFS可以解决枚举子序列问题:给定一个序列,枚举这个序列的所有子序列。因为每个数总有两种状态,选与不选,然后进行递归即可。
枚举从N个整数中选择K个数的方案是子问题。
例题:从序列A(n个数)中选K个数,使得和为x,且序列的平方和最大。 //有边界,提前判断
//序列A中n个数选k个数使得和为x,最大平方和为maxSumSqu #include<cstdio> #include<vector> using namespace std; const int maxn = 10010; int n, k, x, maxSumSqu = -1, A[maxn]; vector<int> temp, ans; //temp用于储存可能的序列 void DFS(int index, int nowK, int sum, int sumSqu) { if (nowK == k && sum == x) { if (sumSqu > maxSumSqu) { maxSumSqu = sumSqu; ans = temp; } return; } if (index == n || nowK > k || sum > x) return; //选index号数 temp.push_back(A[index]); DFS(index + 1, nowK + 1, sum + A[index], sumSqu + A[index] * A[index]); temp.pop_back(); //不选index号数 DFS(index + 1, nowK, sum, sumSqu); } int main() { /* 4 2 6 2 3 3 4 */ /* 10 2 11 2 6 7 8 2 5 0 7 4 5 */ scanf("%d%d%d", &n, &k, &x); //序列A中n个数选K个数,使得和为x for (int i = 0; i < n; i++) { scanf("%d", &A[i]); } DFS(0, 0, 0, 0); for (int i : ans) { printf("%d ", i); } }
假如数可以被重复选择的话,将选index号数的DFS代码改为
DFS(index, nowK + 1, sum + A[index], sumSqu + A[index] * A[index]);
即可,太巧妙了!index可以重复选择,直到不再要的时候,在进入index + 1的选择。
背包问题
有n件物品,每件物品的重量为w[i],价值为c[i]。需要选出若干件物品放入一个容量为V的背包,使得在选入的物品重量和不超过V的情况下,物品总价值最大,求最大价值。n在1到20之间。 //无边界
抽象为DFS问题,分支为选与不选,死胡同为选完n个物品。注意要利用weight<=V这个条件进行剪枝。
//背包问题,使用DFS解决,岔道口:每个物品只有两种状态,放/不放 //死胡同是 超重/物品放完 #include<cstdio> const int maxn = 30; int w[maxn], c[maxn], n, V, MaxValue = -1; void DFS(int index, int nowWeight, int nowValue) { if (index == n)//选择完n件物品后 { //if (nowWeight <= V && nowValue > MaxValue) 将该处的判断可以提前,减少分支 // MaxValue = nowValue; return; } if(nowWeight + w[index] <= V) //判断安全后才会加新的物品 { if (nowValue + c[index] > MaxValue) MaxValue = nowValue + c[index]; DFS(index + 1, nowWeight + w[index], nowValue + c[index]); //选第index件物品 } DFS(index + 1, nowWeight, nowValue); } int main() { /* 5 8 3 5 1 2 2 4 5 2 1 3 */ scanf("%d%d", &n, &V); //有n个物品,最大重量V for (int i = 0; i < n; i++) { scanf("%d", &w[i]); } for (int i = 0; i < n; i++) { scanf("%d", &c[i]); } DFS(0, 0, 0); printf("%d\n", MaxValue); }