Java dfs brute force solution


  • 0
    M

    public class Solution {
    public int findTargetSumWays(int[] nums, int S) {
    // dfs like 282 Expression Add Operators
    if(nums == null || nums.length == 0) return 0;
    List<Integer> result = new ArrayList<Integer>();
    dfs(nums, S, 0, 0, result);
    return result.size();
    }
    public void dfs(int[] nums, int S, int pos, long currsum, List<Integer> result) {
    //exit condition
    if(pos == nums.length) {
    if(currsum == S) {
    int temp = (int) currsum;
    result.add(temp);
    }
    return;
    }

        int value = nums[pos];
        dfs(nums, S, pos+1, currsum + value, result); // +
        dfs(nums, S, pos+1, currsum - value, result); // -
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.