题目描述
研究中心正在研究一种数列,该数列由整数组成,每次可以对相邻的两个数进行相减操作,并删去这两个数,将运算结果替换进去。直到此数列只剩一个数为止。现在此研究中心欲使此最后剩下的数字为目标数,请你帮助他们完成这个任务。 若此数列为{12,10,4,3,5},目标数为4,E(n)表示对第n和第n+1数进行相减并替换。
E(2)={12,6,3,5}(6=10-4)
E(3)={12,6,-2}(-2=3-5)
E(2)={12,8}(8=6-(-2))
E(1)={4}(4=12-8)
则最后达到目的,数列仅剩一目标数,则此过程为:2,3,2,1;
(假设:在运算过程中的所有数都在int范围内)
输入输出格式
输入格式
第一行为N(3≤N≤10),为数列中数的个数。
第二行为M,为目标数。
以下N行每行一个整数,为此数列中的数。
输出格式
一行,输出总共可行方案的数量。
输入输出样例
输入样例
5
4
12
10
4
3
5
输出样例
3
题解
搜索水题,关键是更改序列。
此题如果暴力更改数列的话,时间复杂度是O(n2),我们可以开一个辅助数组来维护序列,这样就可以用O(n)的时间复杂度修改了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include <iostream> #include <algorithm> using namespace std; int n, m; int a[15]; int ans; void DFS(int a[15], int n) { if(n == 1) { if(a[n] == m) ++ans; return; } int b[15]; for(register int i = 1; i < n; ++i) { b[i] = a[i + 1]; } for(register int i = 1; i < n; ++i) { b[i] = a[i] - a[i + 1]; DFS(b, n - 1); b[i] = a[i]; } return; } int main() { cin >> n >> m; for(register int i = 1; i <= n; ++i) { cin >> a[i]; } DFS(a, n); cout << ans; return 0; }