【深度优先搜索】递归、穷举与优化(Memorization)经典题目与C++解答

概念

深度优先搜索算法(Depth-First-Search,DFS)是一种用于遍历或搜索树或图的算法。 这个算法会尽可能深的搜索树的分支。 当节点v的所在边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。 这一过程一直进行到已发现从源节点可达的所有节点为止。

DFS,根据题目的要求,适用于需要穷举所有可能性的情况。一般来说比较易于理解但是算法速度较慢,一般为指数时间,但加以合理的缓存优化(Memorization)可以以牺牲内存为代价提高速度。

题目

题目来源于LeetCode

494. Target Sum

You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.

题解
递归
class Solution {
public:
    int sum;
    int cpt = 0;
    int findTargetSumWays(vector<int>& nums, int S) {
        sum = S;
        recur(nums);
        return cpt;
    }
    
    void recur(vector<int>& nums, int curr = 0, int pos = 0){
        if(pos==nums.size()){
            if(curr == sum)
                ++cpt;
            return;
        }
        
        recur(nums, curr+nums[pos], pos+1);
        recur(nums, curr-nums[pos], pos+1);
    }
};

因为每个节点有两个子节点,故为指数时间。

使用缓存优化的递归
class Solution {
public:
    int sum;
    int findTargetSumWays(vector<int>& nums, int S) {
        sum = S;
        vector<vector<int>> memo(nums.size()+1, vector<int>(2001, 1001));
        return recur(nums, memo);
    }
    
    int recur(vector<int>& nums, vector<vector<int>>& memo, int curr = 0, int pos = 0){
        if(pos==nums.size()){
            if(curr == sum)
                return 1;
            else
                return 0;
        }
        if (memo[pos][curr+1000] != 1001)
            return memo[pos][curr+1000];
        
        int cpt = 0;
        cpt+=recur(nums, memo, curr+nums[pos], pos+1);
        cpt+=recur(nums, memo, curr-nums[pos], pos+1);
        
        memo[pos][curr+1000] = cpt;
        return cpt;
    }
};

时间复杂度从指数降到了多项式时间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值