背包问题(简单回溯)

设有一个背包可以放入的物品重量为S,现有n物品,重量分别为w1,w2,w3……wn。问能否从这n件物品中选择若干件放入背包中,使得放入的重量之和正好为S。如果有满足条件的选择,则此背包问题有解,否则此背包问题无解。

【input】

20 5

1 3 5 7 9

【output】

Yes

分析:

1.假定可以放入背包的总重量为S,物品总个数为n,当前已放入物品的总重量之和sumWeight。

2.依次放入第1,2,3….个物品并计算当前的总重量之和sumWeight

3.在试探的过程中要分三种情况

(a) 如果超过背包的总重量S则回溯,并在回溯的过程中sumWeight要减去当前物品的重量。

(b) 如果小于背包的总重量S,则sumWeight要加上当前物品的重量,并继续向前试探。

(c) 如果等于背包的总重量S则输出结果。

//C++代码
#include<bits/stdc++.h>
using namespace std;
int a[10000],s,n;

bool check(int Sumweigth,int cnt)
{
	
	if(cnt==n)
	{
		return Sumweigth==s;
	}
	if(check(Sumweigth+a[cnt],cnt+1))
	{
		return true; 
	}
	if(check(Sumweigth,cnt+1))
	{
		return true;
	}
	return false ;
}

void solve()
{
	cin>>s>>n;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	if(check(0,0))
	{
		cout<<"Yes"<<endl;
	}
	else
	{
		cout<<"No"<<endl;
	}
}
int main()
{
	solve();
	return 0;
} 

//java代码

import java.util.Scanner;
public class text2 {

	public static int n;
	public static int s;
	public static int [] arr=new int [1000];
	public static boolean check(int Sumweigth,int cnt)
	{
		if(cnt==n)
		{
			return Sumweigth==s;
		}
		if(check(Sumweigth+arr[cnt],cnt+1))
		{
			return true;
		}
		if(check(Sumweigth,cnt+1))
		{
			return true;
		}
		return false;
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		s=sc.nextInt();
		for(int i=0;i<n;i++)
		{
			arr[i]=sc.nextInt();
		}
		if(check(0,0))
		{
			System.out.print("Yes");
		}
		else
		{
			System.out.print("No");
		}
		sc.close();
	}

}

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aurora_U

谢谢你的鼓励,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值