C language reconstruction [494] goals and

Source code for all topics: Git address

topic

给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 +-。对于数组中的任意一个整数,你都可以从 +-中选择一个符号添加在前面。
返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

示例:
输入:nums: [1, 1, 1, 1, 1], S: 3
输出:5
解释:

-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

一共有5种方法让最终目标和为3。
 

提示:
数组非空,且长度不会超过 20 。
初始的数组的和不会超过 1000 。
保证返回的最终结果能被 32 位整数存下。

Program:

  • Marked with the label of dp, the result is that I used the branch backtracking method to do it, and did not use the dp array, but I have this idea
class Solution
{
    
    
public:
    int findTargetSumWays(vector<int> &nums, int S)
    {
    
    
        //得到nums的个数,然后穿begin和end,进行递归
        int len = nums.size();
        return help(0, 0, len - 1, nums, S);
    }

    int help(int now, int begin, int end, vector<int> &nums, int S)
    {
    
    
        int res;
        //走到底,退出
        if (begin == end)
        {
    
    
            res = (nums[begin] + now) == S ? 1 : 0;
            res += (-nums[begin] + now) == S ? 1 : 0;
            return res;
        }
        else
        {
    
    
            //没走到底,继续循环,左右两侧算出后返回
            res = help(now + nums[begin], begin + 1, end, nums, S);
            res += help(now - nums[begin], begin + 1, end, nums, S);
            return res;
        }
    }
};
Complexity calculation
  • Time complexity: O(n2)
  • Space complexity: O(n)

Guess you like

Origin blog.csdn.net/symuamua/article/details/114578341