share my DFS solution using JAVA!


  • 0
    T
    public class Solution {
        int count=0;
        public int findTargetSumWays(int[] nums, int S) {
            int sum=0;
            for(int ele:nums){
                sum+=ele;
            }
            if(sum<S) return 0;
            helper(nums,S,0,sum);
            return count;
        }
        
        public void helper(int[] nums,int S,int index,int cursum){
            if(cursum<S){
                return;
            }
            
            if(index==nums.length){
                if(cursum==S){
                    count++;
                }
            }else{
                helper(nums,S,index+1,cursum);
                helper(nums,S,index+1,cursum-2*nums[index]);
            }
            
        }
    }
    

Log in to reply
 

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