Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3024
一个人的身影
一个人的身影 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:06

    function solve(n){
        let DP = [];
    
         DP[0] = DP[1] = DP[2] = 1;
         DP[3] = 2;
    
        for (let i = 4; i <= n; i++) {
          DP[i] = DP[i-1] + DP[i-3] + DP[i-4];
        }
        return DP[n]
    }
    
    console.log(solve(5))
    

    This is a Dynamic Solution for JS to tell how many ways anyone can get the certain sum. This can be the right solution if you think about time and space complexity.

提交回复
热议问题