Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3050
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  执笔经年
    2020-11-21 07:08

    import java.util.*;
    
    public class Main{
    
         int recursionDepth = 0;
         private int[][] memo;
    
         public static void main(String []args){
             int[] nums = new int[] {5,2,4,3,1};
             int N = nums.length;
             Main main =  new Main();
             main.memo = new int[N+1][N+1];
             main._findCombo(0, N-1,nums, 8, 0, new LinkedList() );
             System.out.println(main.recursionDepth);
         }
    
    
           private void _findCombo(
               int from,
               int to,
               int[] nums,
               int targetSum,
               int currentSum,
               LinkedList list){
    
                if(memo[from][to] != 0) {
                    currentSum = currentSum + memo[from][to];
                }
    
                if(currentSum > targetSum) {
                    return;
                }
    
                if(currentSum ==  targetSum) {
                    System.out.println("Found - " +list);
                    return;
                }
    
                recursionDepth++;
    
               for(int i= from ; i <= to; i++){
                   list.add(nums[i]);
                   memo[from][i] = currentSum + nums[i];
                   _findCombo(i+1, to,nums, targetSum, memo[from][i], list);
                    list.removeLast();
               }
    
         }
    }
    

提交回复
热议问题