![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1aa3e5ce9593687148790b3ae30b6e80.png)
- 铁憨憨的我第一次做出来比较难看。。。如下把递归写得毫无美感:
public class FindTargetSumWays {
private int count = 0;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int findTargetSumWays(int[] nums, int S) {
if(nums == null || nums.length == 0)
return 0;
findTargetSumHelper(nums, S, 0);
return getCount();
}
private void findTargetSumHelper(int[] nums, int S,int index)
{
if(S == 0 && index == nums.length)
{
count++;
return;
}
else if(index == nums.length)
return;
int i = index + 1;
findTargetSumHelper(nums,S+nums[index], i);
findTargetSumHelper(nums,S-nums[index], i);
}
public static void main(String[] args)
{
int[] nums = {1, 1, 1, 1, 1};
int S = 3;
FindTargetSumWays findTargetSumWays = new FindTargetSumWays();
findTargetSumWays.findTargetSumWays(nums,3);
System.out.println("共有 " + findTargetSumWays.getCount() + " 种方法");
}
}
- 修改,想想不需要用count来计数,毕竟深度搜索到底,能成功就是1不能就是0,那么直接将0、1作为递归函数的约束条件在最后一层返回,累加起来即可作为最终方法数:
public class FindTargetSumWays {
public int findTargetSumWays(int[] nums, int S) {
return findTargetSumHelper(nums, S, 0);
}
private int findTargetSumHelper(int[] nums, int S, int index)
{
if(nums.length == index)
return S == 0 ? 1 : 0;
return findTargetSumHelper(nums,S + nums[index],index + 1)
+findTargetSumHelper(nums, S - nums[index], index + 1);
}
public static void main(String[] args)
{
int[] nums = {1, 1, 1, 1, 1};
int S = 3;
FindTargetSumWays findTargetSumWays = new FindTargetSumWays();
int res = findTargetSumWays.findTargetSumWays(nums,3);
System.out.println("共有 " + res + " 种方法");
}
}
- 动态规划
这个动态规划还是把我难倒了,看了别人的代码才写得出来。。
public int findTargetSumWaysDP(int[] nums, int target) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if(sum < target || (sum+target)%2 == 1){
return 0;
}
target = (target + sum) / 2;
int[] dp = new int[target + 1];
dp[0] = 1;
for (int num : nums) {
for (int i = target; i >= num; i--) {
dp[i] += dp[i - num];
}
}
return dp[target];
}