Easy and flexible code with DFS (JAVA)


  • 0

    My Code is super easy and easily generalized.

    public class Solution {
        int count = 0;
        public int numberOfArithmeticSlices(int[] A) {
            for(int i = 0; i < A.length; i++)
                search(A, i, new LinkedList<>());
            return count;
        }
        private void search(int[] nums, int pos, List<Integer> tmp){
            if(tmp.size() >= 3){
                int preGap = tmp.get(1) - tmp.get(0);
                int curGap = tmp.get(tmp.size()-1) - tmp.get(tmp.size()-2);
                if(preGap == curGap) {
                    count++;
                }
                else return;
            }
            if(pos < nums.length){
                tmp.add(nums[pos]);
                search(nums, pos + 1, tmp);
                tmp.remove(tmp.size()-1);
            }
        }
    }
    

Log in to reply
 

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