唉,太佩服人家的思路了,没做过这题是真的不会啊。
#include<iostream>
using namespace std;
int a[10001];
int f(int n,int m)
{
if(m==0||m-a[n]==0)return 1;
if(n==1&&m-a[n]!=0)return 0;
else return f(n-1,m)||f(n-1,m-a[n]);
}
int main()
{
int n,m;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cin>>m;
if(f(n,m)==1)
cout<<"yes";
else cout<<"no";
return 0;
}
import java.util.Scanner;
public class GroupSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int start = scanner .nextInt();
int [] nums = new int[3];
for(int i=0; i<3; i++){
nums[i] = scanner.nextInt();
}
int target = scanner .nextInt();
System.out.println(groupSum(start,nums,target));
}
//调用递归
public static boolean groupSum(int start, int[] nums, int target) {
if (start >= nums.length)
return (target == 0);
if (groupSum(start + 1, nums, target - nums[start]))
return true;
if (groupSum(start + 1, nums, target))
return true;
return false;
}
}
原文链接:https://blog.csdn.net/tupu8617/article/details/78055846