Leetcode 494. Target SumAdd to List

    xiaoxiao2021-03-25  104

    题目: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.

    解题思路:将题目的意思转化为取输入的数组中的每一个元素本身或者其相反数,即要么取这个元素,要么取其相反数,取值间互不影响,将这些数相加得到的和恰好为给定的值的取值方法有几种。假设输入的数组的长度为n,那么一共有2为底指数为n那么多次取法,可以以一张图片来说明(不知道这次的图片能不能传上去,上次的就没传成功。。。。反正下面应该有张图才对)。

    上图以数组a={a0,a1,a2}为例,总有八种取法:+a0+a1+a2,+a0+a1-a2,+a0-a1+a2,+a0-a1-a2,-a0+a1+a2,-a0+a1-a2,-a0-a1+a2,-a0-a1-a2;将每种取法得到的和与输入的目标值作比较,每当有一种取法的和等于目标值,则++count,最后输出count值;以下程序是根据DFS算法写出来的,与一般的DFS算法用法不同的是这里不标记已访问的点,一个点被访问过之后仍然能继续访问。代码如下:

    class Solution { private: bool isTarget(int s, int sum, int &count, vector<int>::iterator iter, vector<int>::iterator iterend){ int temp; temp = *iter; if(iter != iterend -1){ int left , right; left = isTarget( s, sum - temp, count, iter + 1 , iterend); right = isTarget( s, sum + temp, count, iter + 1, iterend); return (left||right); } else{ int flag = 0; if(sum - temp == s){ ++count; flag = 1; } if(sum + temp == s){ ++count; flag = 1; } if(flag == 1) return 1; return 0; } } public: int findTargetSumWays(vector<int>& nums, int S) { int count = 0; int sum = 0; vector<int>::iterator iter = nums.begin() ,iterend = nums.end(); if(isTarget( S, sum, count,iter,iterend)) return count; else return 0; } };

    转载请注明原文地址: https://ju.6miu.com/read-15571.html

    最新回复(0)