题目:现有给定升序排列的整形数组a[n]和整数S,需要在整型数组中找到任意个小标,使得各小标对应数字之和为S,输出所有可能的下标组合。
例如:
数组 1,4,8,10,12,15,22,25,31, X=30 可得
下标: 2,6 : a[2] + a[6] = 30
下标:0,1,3,5 : a[0] + a[1] + a[3] + a[5] = 30
...
使用下面的函数原型
int searchNumbers(int data[], unsigned int length, int sum)
[思路] 回溯法,每个位置有两种情况可取可不取,可得出所有的情况。
代码如下:
#include<iostream> #include<vector> using namespace std; void DFS(int data[], unsigned int length, int target, int &sum, int depth, vector<int> &v, vector<vector<int> >&vv) { if (depth == length) return; if (sum == target) { vv.push_back(v); } if (sum < target) { DFS(data, length, target, sum, depth + 1, v, vv); sum = sum + data[depth]; v.push_back(depth); DFS(data, length, target, sum, depth + 1, v, vv); sum = sum - data[depth]; v.pop_back(); } } int searchNumbers(int data[], unsigned int length, int target) { int sum = 0; int depth = 0; vector<int> v; vector<vector<int> >vv; DFS(data, length, target, sum, depth, v, vv); for (int i = 0; i < vv.size(); i++) { v = vv[i]; for (int j = 0; j < v.size(); j++) cout << v[j] << " "; cout << endl; } return vv.size(); } int main() { int data[] = {1,4,8,10,12,15,22,25,31}; unsigned int length = sizeof(data) / sizeof(data[0]); int target = 30; int answer = searchNumbers(data, length, target); cout << "total number: " << answer << endl; return 0; }