首页 > 技术文章 > 经典dfs(depth-first search)

chinashenkai 2016-02-22 19:07 原文

DFS主要在于参数的改变;
样例输入:
n=4                //给定n个数字
a={1,2,4,7}    //输入n个数据
k=15              //目标数字


样例输出:
No


题意:
给定的数字在不重复使用的前提下能否达到目标,能输出Yes,否输出No



#include<algorithm>
#include<iostream>


using namespace std;


int n,k,a[10000];
bool dfs(int i,int sum)
{
    if(i==n) return sum==k;
    if(dfs(i+1,sum)) return true;
    if(dfs(i+1,sum+a[i])) return true;
    return false;
}


int main()
{
    cin >> n;
    for(int i=0;i<n;i++)
        cin >> a[i];
    cin >> k;
    if(dfs(0,0)) cout<<"Yes"<<endl;
    cout <<"No"<<endl;
}


推荐阅读