P30:部分和问题
/* P30页:部分和问题 核心:用递归实现深度优先搜索是很方便的事情 问题:n个数中选出任意个数使得和为k, 找到返回find,灭有返回not find */ #include <iostream> #include <iterator> #include <vector> using namespace std; const int NUM = 1010; int n, k; int a[NUM]; vector<int> s; bool bfs(int i, int sum) { if(i == n) return sum == k; if (bfs(i+1, sum)) return true; if (bfs(i+1, sum+a[i])) { s.insert(s.end(), a[i]); return true; } return false; } int main(void) { cin >> n >> k; for(int i = 0; i < n; i++) cin >> a[i]; if (bfs(0, 0)) { copy(s.begin(), s.end(), ostream_iterator<int>(cout, "+")); cout << "=" << k << "\n" << "find" << "\n"; } else cout << "not find"; return 0; }