题目:
解析:
决策树:
代码设计:
代码:
写法一:path为全局变量
private int ret,path,aim;
public int findTargetSumWays(int[] nums, int target) {
aim = target;
dfs(nums,0);
return ret;
}
private void dfs(int[] nums, int pos){
if(pos == nums.length){
if(path == aim) ret++;
return;
}
//添加 '+'
path += nums[pos];
dfs(nums,pos+1);
path -= nums[pos];//回溯
//添加 '-'
path -= nums[pos];
dfs(nums,pos+1);
path += nums[pos];//回溯
}
写法二:path作为参数
private int ret,aim;
public int findTargetSumWays(int[] nums, int target) {
aim = target;
dfs(nums,0,0);
return ret;
}
private void dfs(int[] nums, int pos,int path){
if(pos == nums.length){
if(path == aim) ret++;
return;
}
//添加 '+'
dfs(nums, pos+1, path + nums[pos]);
//添加 '-'
dfs(nums, pos+1, path - nums[pos]);
}