Backtracking solution java easy


  • 1
    G
    public class Solution {
        public int findTargetSumWays(int[] nums, int S) {
            int sum = 0;
            int[] arr = new int[1];
            helper(nums, S, arr,0,0);
            return arr[0];
        }
        
        public void helper(int[] nums, int S, int[] arr,int sum, int start){
            if(start==nums.length){
                if(sum == S){
                    arr[0]++;
                }
                return;
            }
                //这里千万不要加for循环,因为我们只是从index0开始
                helper(nums,S,arr,sum-nums[start],start+1);
                helper(nums,S,arr,sum+nums[start],start+1);
            
        }
    }

Log in to reply
 

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