题解 | #目标和#
目标和
https://www.nowcoder.com/practice/7fc06e2162f048658252fac542fcb1e8
using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ public int findTargetSumWays (List<int> nums, int target) { // write code here if (nums == null || nums.Count == 0) return 0; int nCount = 0; DG(nums, target, 0, ref nCount, 0); return nCount; } public void DG(List<int> nums, int target, int nCurIndex, ref int nCount, int nCurR) { // write code here if(nCurIndex >= nums.Count) { if (nCurR == target) nCount++; return; } //+加法 DG(nums, target, nCurIndex + 1, ref nCount, nCurR + nums[nCurIndex]); //+减法 DG(nums, target, nCurIndex + 1, ref nCount, nCurR - nums[nCurIndex]); } }