#include#include #include using namespace std; int n, r,ans[100]; void dfs(int u,int step) { if (u <= 0)return; if (step == r) { for (int i = 1; i < r; i++) printf(%d, ans[i]); printf(%d ,u); return; } else { ans[step] = u; for (int i = 1;i<=n;i++) dfs(u - i, step + 1); } } int main() { while (~scanf(%d%d, &n, &r)) { for (int i = n; i >= r; i--) { dfs(i,1); } } return 0; }
5 3
543 542 541 532 531 521 432 431 421 321
#include#include #include #include using namespace std; #define inf 0x3f3f3f3f int n,a[1000],sum,ans; void dfs(int u,int pos) { ans = min(ans, abs(sum - 2*u)); if (pos == n)return; dfs(u + a[pos], pos + 1); dfs(u, pos + 1); } int main() { while (~scanf(%d, &n)) { ans = inf; sum = 0; for (int i = 1; i <= n; i++) { scanf(%d, a + i); sum += a[i]; } dfs(0,1); printf(%d , ans); } return 0; }
5 5 8 13 27 14
3
這一題可以使用0-1背包來做,也可以遞歸的建一個搜索二叉樹,遞歸搜索的時間復雜度為2^n。