| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [View Raw Code] [Original HTTPS Page] |
Visit original link: 494. Target Sum - LeetCode Python/Java/C++/JS/C#/Go/Ruby Solutions for a better experience!
LeetCode link: 494. Target Sum, difficulty: Medium.
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.
Return the number of different expressions that you can build, which evaluates to target.
Input: nums = [1,1,1,1,1], target = 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
Input: nums = [1], target = 1
Output: 1
This problem is quite difficult if you have not solved similar problems before. So before you start working on this question, it is recommended that you first work on another relatively simple question 416. Partition Equal Subset Sum that is similar to this one.
"Dynamic Programming" requires the use of the dp array to store the results. The value of dp[i][j] can be converted from its previous (or multiple) values through a formula. Therefore, the value of dp[i][j] is derived step by step, and it is related to the previous dp record value.
After reading the above, do you feel that "dynamic programming" is not that difficult? Try to solve this problem. 🤗
Determine the meaning of the dp[j]
Determine the dp array's initial value
Use an example. We didn't use the Example 1: Input: nums = [1,1,1,1,1], target = 3 because it is too special and is not a good example for deriving a formula.
I made up an example: nums = [1,2,1,2], target = 4.
First, determine the size of the knapsack.
Second, determine what are the items. The items are the nums in this problem.
So after initialization, the 'dp' array would be: # 0 1 2 3 4 5 6 # 1 0 0 0 0 0 0 # dp # 1 # 2 # 1 # 2
dp[0] is set to 1, indicating that an empty knapsack can be achieved by not using any nums. In addition, it is used as the starting value, and the subsequent dp[j] will depend on it. If it is 0, all values of dp[j] will be 0.
dp[j] = 0 (j != 0), indicating that it is impossible to get j with no nums.
According to an example, fill in the dp grid data "in order".
1. Use the first num '1'. # 0 1 2 3 4 5 6 # 1 0 0 0 0 0 0 # 1 0 1 0 0 0 0 0 # dp # 2 # 1 # 2
2. Use the second num '2'. # 0 1 2 3 4 5 6 # 1 0 0 0 0 0 0 # 1 0 1 0 0 0 0 0 # 2 0 1 0 1 0 0 0 # 1 # 2
3. Use the third num '1'. # 0 1 2 3 4 5 6 # 1 0 0 0 0 0 0 # 1 0 1 0 0 0 0 0 # 2 0 1 0 1 0 0 0 # 1 2 0 2 0 1 0 0 # 2
4. Use the fourth num '2'. # 0 1 2 3 4 5 6 # 1 0 0 0 0 0 0 # 1 0 1 0 0 0 0 0 # 2 0 1 0 1 0 0 0 # 1 2 0 2 0 1 0 0 # 2 4 0 3 0 2 0 1 # dp
According to the dp grid data, derive the "recursive formula".
dp[j] = dp[abs(j - nums[i])] + dp[j + nums[i]]Write a program and print the dp array. If it is not as expected, adjust it.
public class Solution
{
public int FindTargetSumWays(int[] nums, int target)
{
target = Math.Abs(target);
var dp = new int[Math.Max(nums.Sum(), target) + 1];
dp[0] = 1;
foreach (var num in nums)
{
var dc = (int[])dp.Clone();
for (var j = 0; j < dp.Length; j++)
{
dp[j] = dc[Math.Abs(j - num)] + (j + num < dp.Length ? dc[j + num] : 0);
}
}
return dp[target];
}
}class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
target = abs(target)
dp = [0] * (max(sum(nums), target) + 1)
dp[0] = 1
for num in nums:
dc = dp.copy()
for j in range(len(dp)):
dp[j] = dc[abs(j - num)] + (dc[j + num] if j + num < len(dp) else 0)
return dp[target]class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
auto sum = reduce(nums.begin(), nums.end());
target = abs(target);
auto dp = vector<int>(max(sum, target) + 1);
dp[0] = 1;
for (auto num : nums) {
auto dc = dp;
for (auto j = 0; j < dp.size(); j++) {
dp[j] = dc[abs(j - num)] + (j + num < dp.size() ? dc[j + num] : 0);
}
}
return dp[target];
}
};class Solution {
public int findTargetSumWays(int[] nums, int target) {
var sum = IntStream.of(nums).sum();
target = Math.abs(target);
var dp = new int[Math.max(sum, target) + 1];
dp[0] = 1;
for (var num : nums) {
var dc = dp.clone();
for (var j = 0; j < dp.length; j++) {
dp[j] = dc[Math.abs(j - num)] + (j + num < dp.length ? dc[j + num] : 0);
}
}
return dp[target];
}
}var findTargetSumWays = function (nums, target) {
target = Math.abs(target)
const dp = Array(Math.max(_.sum(nums), target) + 1).fill(0)
dp[0] = 1
for (const num of nums) {
const dc = [...dp]
for (let j = 0; j < dp.length; j++) {
dp[j] = dc[Math.abs(j - num)] + (j + num < dp.length ? dc[j + num] : 0)
}
}
return dp[target]
};func findTargetSumWays(nums []int, target int) int {
sum := 0
for _, num := range nums {
sum += num
}
target = int(math.Abs(float64(target)))
dp := make([]int, max(sum, target) + 1)
dp[0] = 1
for _, num := range nums {
dc := slices.Clone(dp)
for j := 0; j < len(dp); j++ {
addition := 0
if j + num < len(dp) {
addition = dc[j + num]
}
dp[j] = dc[int(math.Abs(float64((j - num))))] + addition
}
}
return dp[target]
}def find_target_sum_ways(nums, target)
target = target.abs
dp = Array.new([ nums.sum, target ].max + 1, 0)
dp[0] = 1
nums.each do |num|
dc = dp.clone
dp.each_with_index do |_, j|
dp[j] = dc[(j - num).abs] + (j + num < dp.size ? dc[j + num] : 0)
end
end
dp[target]
end// Welcome to create a PR to complete the code of this language, thanks!🚀 Level Up Your Developer Identity
While mastering algorithms is key, showcasing your talent is what gets you hired.
We recommend leader.me — the ultimate all-in-one personal branding platform for programmers.
The All-In-One Career Powerhouse:
- 📄 Resume, Portfolio & Blog: Integrate your skills, GitHub projects, and writing into one stunning site.
- 🌐 Free Custom Domain: Bind your own personal domain for free—forever.
- ✨ Premium Subdomains: Stand out with elite tech handle like name.leader.me.
Visit original link: 494. Target Sum - LeetCode Python/Java/C++/JS/C#/Go/Ruby Solutions for a better experience!
GitHub repository: leetcode-python-java.
| Back | FazBrowse Home | New Git URL |