[力扣c++实现] 494. 目标和

494. 目标和

难度中等900收藏分享切换为英文接收动态反馈

给你一个整数数组 nums 和一个整数 target

向数组中的每个整数前添加 '+''-' ,然后串联起所有整数,可以构造一个 表达式

  • 例如,nums = [2, 1] ,可以在 2 之前添加 '+' ,在 1 之前添加 '-' ,然后串联起来得到表达式 "+2-1"

返回可以通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。

示例 1:

输入:nums = [1,1,1,1,1], target = 3
输出:5
解释:一共有 5 种方法让最终目标和为 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
+1 + 1 + 1 + 1 - 1 = 3

示例 2:

输入:nums = [1], target = 1
输出:1

提示:

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums[i]) <= 1000
  • -1000 <= target <= 1000

1. c++

/*
 * 2021-09-19 16:22
*/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

class Solution {
public:
  void dfs(const vector<int>& nums,const int target,int index,long tmptarget,int& times)
  {
    if (index == nums.size())
    {
      if (tmptarget == target)
      {
        ++times;
      }
      return;
    }
    
    dfs(nums,target,index+1,tmptarget + nums[index],times);
    dfs(nums,target,index+1,tmptarget - nums[index],times);
  }

public:
  int findTargetSumWays(vector<int>& nums, int target) {
    long tmptarget = 0;
    int index = 0;
    int times = 0;
    
    dfs(nums,target,index,tmptarget,times);
    return times;
  }

}; 
 
int main()
{
 	Solution s_obj;
  int tmp = 0;
  int target = 0;
  int result = 0;
  vector<int> nums;
  string inputline;
  
  cout<<"input your sequnce: "<<endl;
  getline(cin,inputline);
  
  istringstream stream(inputline);
  
  while (stream >> tmp)
  {
    nums.push_back(tmp);
  }

  cout<<"input target: ";
  cin>>target;

  result = s_obj.findTargetSumWays(nums,target);
  cout<<"the result: "<<result<<endl;
	
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值