Given an input array find all subarrays with given sum K

前端 未结 9 1221
梦如初夏
梦如初夏 2020-12-23 10:03

Given an input array we can find a single sub-array which sums to K (given) in linear time, by keeping track of sum found so far and the start position. If the current sum b

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 10:31

    This problem is very similar to the combination problem solved here: http://introcs.cs.princeton.edu/java/23recursion/Combinations.java.html

    Here is my solution:

    public static void main(String[] args) {
        int [] input = {-10, 0, 5, 10, 15, 20, 30};
        int expectedSum = 20;
    
        combination(new SumObj(new int[0]), new SumObj(input), expectedSum);
    }
    
    private static void combination(SumObj prefixSumObj, SumObj remainingSumObj, int expectedSum){
        if(prefixSumObj.getSum() == expectedSum){
            System.out.println(Arrays.toString(prefixSumObj.getElements()));
        } 
    
        for(int i=0; i< remainingSumObj.getElements().length ; i++){
            // prepare new prefix
            int [] newPrefixSumInput = new int[prefixSumObj.getElements().length + 1];
            System.arraycopy(prefixSumObj.getElements(), 0, newPrefixSumInput, 0, prefixSumObj.getElements().length);
            newPrefixSumInput[prefixSumObj.getElements().length] = remainingSumObj.getElements()[i];
            SumObj newPrefixSumObj = new SumObj(newPrefixSumInput);
    
            // prepare new remaining
            int [] newRemainingSumInput = new int[remainingSumObj.getElements().length - i - 1];            
            System.arraycopy(remainingSumObj.getElements(), i+1, newRemainingSumInput, 0, remainingSumObj.getElements().length - i - 1);
            SumObj newRemainingSumObj = new SumObj(newRemainingSumInput);
    
            combination(newPrefixSumObj, newRemainingSumObj, expectedSum);
        }
    }
    
    private static class SumObj {
        private int[] elements;
        private int sum;
    
        public SumObj(int[] elements) {
            this.elements = elements;
            this.sum = computeSum();
        }
    
        public int[] getElements() {
            return elements;
        }
    
        public int getSum() {
            return sum;
        }
    
        private int computeSum(){
            int tempSum = 0;
            for(int i=0; i< elements.length; i++){
                tempSum += elements[i];
            }
            return tempSum;
        }
    }
    

提交回复
热议问题