加成序列(迭代加深)
迭代加深
170.加成序列

样例输入:
5
7
12
15
77
0
样例输出:
1 2 4 5
1 2 4 6 7
1 2 4 8 12
1 2 4 5 10 15
1 2 4 8 9 17 34 68 77
代码模板:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
int path[N];
bool dfs(int u, int k)
{
if (u == k) return path[u - 1] == n;
bool st[N] = {0}; //排除等效冗余 两个数相加有重复数的可能
for (int i = u - 1; i >= 0; i -- ) //优化搜索顺序 优先从大到小枚举
for (int j = i; j >= 0; j -- )
{
int s = path[i] + path[j];
if (s > n || s <= path[u - 1] || st[s]) continue;
st[s] = true;
path[u] = s;
if (dfs(u + 1, k)) return true;
}
return false;
}
int main()
{
path[0] = 1;
while (cin >> n, n)
{
int k = 1;
while (!dfs(1, k)) k ++ ;
for (int i = 0; i < k; i ++ ) cout << path[i] << ' ';
cout << endl;
}
return 0;
}

浙公网安备 33010602011771号