回溯法求矩阵中和为定值的组合
题目描述:
给定整数数组A,求和为sum的所有组合,并输出。还有一种类似题目是,求所有组合的个数。
要求:输出子数组不能改变元素在原始数组中的相对位置。
题目要求不能改变相对位置表示不能对原始数组排序。
C++实现如下:
void sumn(vector<int> &A,int start,int end,int sum,vector<int> &tmp,vector<vector<int>> &res){
if (start == end && sum == 0)
{
res.push_back(tmp);
}
else if (start == end) return;
else{
if (sum >= A[start]){
tmp.push_back(A[start]);
sumn(A, start + 1, end, sum - A[start], tmp, res);
tmp.pop_back();
}
sumn(A, start + 1, end, sum, tmp, res);
}
}