这是一个递归的解决方案,用于寻找一个集合的子集的数量(元素的和等于给定的和).为什么它只返回1


//this approach is based on finding all the subsets of a set having n elements by finding subsets of n-1 elements. and so on through recursion..
int sum_subset(int set[], vector<int>& subset, int sum, int n, int l=0)
{
//for  edge case of sum=0
if (sum = 0) return 1;
int s = 0;
//base condition of recursion
if (l == n) {
for (int x:subset) {
s += x;
}
return (s==sum)? 1: 0;
}
//calling the recursion for ->not including the nth element of the set of n elements in the subset of n-1 elements
int a = sum_subset(set, subset, sum, n, l+1);
//including nth element in the subset
subset.push_back(set[l]);

//calling the recursion for -> including the nth element of the set of n elements in the subset of n-1 elements
int b = sum_subset(set, subset, sum, n, l+1);
return a + b;
}  
int main() {
int n;
cout << "enter the size of set" << endl;
cin >> n;
int set[n];
cout << "enter the set elements" << endl;
for(int i = 0; i < n; i++) {
cin >> set[i];
}
cout << "enter the sum " << endl;
int sum;
cin >> sum;
vector<int> subset{0};
int ans = sum_subset(set, subset, sum, n);
cout << "subsets having sum =" << sum << "are->" << ans << endl;
}
//output
enter the size of set
5
enter the set elements
1
2
2
1
3
enter the sum 
3
subsets having sum =3are->1

您正在为sum变量分配值0,而不是比较值:

//for  edge case of sum=0
if (sum = 0) return 1;
int s = 0;

这本身就隐藏了另一个问题:永远不会从subset向量中移除值。例如,第一次将值推送到子集时,使子集等于{3}。然后你只需要添加越来越多的值;子集";永远不会给你3的总和。

还有一个问题不会影响你的程序,但很重要。在下面的行中,你没有创建一个空向量,但你创建了一个包含一个零元素的向量,该向量等于{0}:

vector<int> subset{0};

最新更新