一个简单的思考方式是5+6+7+8的和可以看成(5+6+7)+8,所以就可以想到动态规划的方法
设一个二维数组,i代表数列长度为(i+1),j代表数列首部数字。
比如说求和为5的连续正数数列
class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { vector<vector<int> > ret; int** array = new int*[sum - 1]; for (int i = 0; i < sum - 1; i++) { array[i] = new int[sum - 1]; } for (int i = 0; i < sum -1; i++) { array[0][i] = i + 1; } for (int i = 1; i < sum - 1; i++) { for (int j = 0; j < sum - 2; j++) { array[i][j] = array[i -1][j] + array[0][j + i]; if (array[i][j] > sum) { break; } if (array[i][j] == sum) { vector<int> vec; vec.reserve(i + 1); for (int k = j + 1;k <= i + j + 1;k++) { vec.push_back(k); } ret.push_back(vec); } } } vector<vector<int> >realRet; realRet.reserve(ret.size()); for (int i = ret.size() - 1; i >= 0; i--) { realRet.push_back(ret[i]); } return realRet; } };