深度优先算法:首先想到递归;再次找到起始状态;最后找到使递归终止的条件;

这个题的思路比较简单:对于每个数字都有两种可能,选中或者是不选中,所以从第一个开始求,要么选中....要么不选中....
终止条件就是到达最后一个数字的时候,就要终止了。(至于终止时候返回值要注意一下);
怎么写递归函数:首先要有参数可以改变,然后通过该参数终止递归;将需要改变的值都通过形参改变;

 

/*************************************************************************
	> File Name: part_sum.cpp
	> Author: 
	> Mail: 
	> Created Time: 2015年11月11日 星期三 20时16分46秒
 ************************************************************************/

#include<iostream>
using namespace std;
const int MAXNUM = 20;

int arr[MAXNUM];
int n, k;

void input_data(int *n, int *k, int *arr)
{
    cout << "n = ";
    cin >> *n;
    cout << "a = {";
    for (int i = 0; i < *n; i++){
        cin >> arr[i];
        cin.get();
        cin.get();
    }
    cout << "k = ";
    cin >> *k;
}

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

    return false;
}

void solve()
{
    if (dfs(0, 0))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;    
}

int main()
{
    input_data(&n, &k, arr);

    solve();

    return 0;
}

posted on 2015-11-11 21:08  Linux-ever  阅读(429)  评论(0编辑  收藏  举报