Subsequence sum

后端 未结 5 1197
天命终不由人
天命终不由人 2021-01-30 18:23

Given an array of integers eg [1, 2, -3, 1] find whether there is a sub-sequence that sums to 0 and return it (eg [1, 2, -3] or [2,

5条回答
  •  暖寄归人
    2021-01-30 18:59

    Below is the java implementation of the solution suggested by @Fabricio

        public static int countAllSubSequenceForZeroSum(int[] array) {
        int count = 0;
        Map encounteredSum = new HashMap<>();
        int prev = array[0];
        if(prev == 0) {
            count++;
            System.out.println("Found at index: "+0);
        }
        for (int i = 1; i < array.length; i++) {
            prev += array[i];
            if(encounteredSum.containsKey(prev)) {
                System.out.println("Found at index: "+i+ " start index: "+encounteredSum.get(prev));
                printSequenceForZeroSum(array, i);
                count++;
            } else {
                encounteredSum.put(prev, i);
            }
        }
        return count;
    }
    
    public static void printSequenceForZeroSum(int[] array, int endIndex) {
        int sum = array[endIndex];
        while(sum!=0) {
            System.out.print(array[endIndex]+ "  ");
            sum += array[--endIndex];
        }
        System.out.println(array[endIndex]);
    }
    

提交回复
热议问题