?LeetCode刷題實戰(zhàn)494:目標和
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to 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
解題

class?Solution?{
public:
????int?findTargetSumWays(vector<int>& nums, int?S)?{
????????int?sum = 0;
????????for(int?i=0;i????????????sum += nums[i];
????????if(abs(S) > abs(sum))
????????????return?0;
????????int?t = sum * 2?+ 1; //注意t的取值
????????int?len = nums.size();
????????vector<vector<int>> dp(len,vector<int>(t));
????????if(nums[0] == 0)
????????????dp[0][sum] = 2;
????????else{
????????????dp[0][sum + nums[0]] = 1;
????????????dp[0][sum - nums[0]] = 1;
????????}
????????for(int?i = 1;i < nums.size();i++)
????????????for(int?j = 0;j < t;j++){
????????????????int?l = (j - nums[i]) >= 0?? j-nums[i] : 0;
????????????????int?r = (j + nums[i]) < t ? j+nums[i] : 0;
????????????????dp[i][j] = dp[i-1][l] + dp[i-1][r];
????????????}
????????return?dp[nums.size()-1][sum + S];
????}
};
LeetCode刷題實戰(zhàn)485:最大連續(xù) 1 的個數(shù)
LeetCode刷題實戰(zhàn)486:預(yù)測贏家
LeetCode刷題實戰(zhàn)487:最大連續(xù)1的個數(shù) II
LeetCode刷題實戰(zhàn)492:構(gòu)造矩形
LeetCode刷題實戰(zhàn)493:翻轉(zhuǎn)對
