Hi bobo老师,
对于494. Target Sum 这道题目,我使用了记忆化搜索的形式解决了,并且accepted, 但是想不出怎么用dp来解决,能给一些思路么?
下面是我的记忆化搜索的方法:
class Solution {
class Pair {
int index;
int target;
public Pair(int index, int target) {
this.index = index;
this.target = target;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return index == pair.index && target == pair.target;
}
@Override
public int hashCode() {
return Objects.hash(index, target);
}
}
public int findTargetSumWays(int[] nums, int target) {
if (nums.length == 0){
return 0;
}
// use memory to save the method consider from index i to sum the target
Map<Pair,Integer> memory = new HashMap<>();
return ways(nums, 0 , target , memory);
}
public int ways(int[] nums, int index, int target, Map<Pair,Integer> memory){
if (index == nums.length -1){
int res = 0;
if (target == nums[index]){
res++;
}
if (target == -nums[index]){
res++;
}
return res;
}
Pair pair = new Pair(index,target);
if (memory.get(pair) != null){
return memory.get(pair);
}
int result = 0;
Pair pair1 = new Pair(index + 1, target - nums[index]);
Pair pair2 = new Pair(index + 1, target + nums[index]);
if (memory.get(pair1) != null){
result = result + memory.get(pair1);
} else {
int a = ways(nums , index + 1 , target - nums[index] , memory);
memory.put(pair1 , a);
result = result + a;
}
if (memory.get(pair2) != null){
result = result + memory.get(pair2);
} else {
int b = ways(nums , index + 1 , target + nums[index] , memory);
memory.put(pair2, b);
result = result + b;
}
return result;
}
}