Combination Sum变体[1]

Number of ways that you can get the target from a list of numbers.
order doesn’t matter
recursion:

        public int combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            int count = 0;
            return helper(candidates, 0, target);
        }

        public int helper(int[] candidates, int position, int target) {
            if (target == 0) {
                return 1;
            } else if (target < 0) {
                return 0;
            }

            for (int i = position; i < candidates.length; i++) {
               if (candidates[i] > target) {
                   continue;
                }
                return helper(candidates, i, target - candidates[i]) 
                + helper(candidates, i + 1, target);
           }
           return 0;
    }

dynamic programming method 1:

    public int getNumOfWays(int[] inputs, int target) {
        if (inputs == null || inputs.length == 0) {
            return 0;
        }

        //    0 1 2 3 4
        // 0  1 0 0 0 0
        // 1  1 1 1 1 1
        // 2  1 0 2
        // 3  1
        int len = inputs.length;
        int[][] table = new int[len + 1][target + 1];
        for (int i = 0; i <= target; i++) {
            table[0][i] = 0;
        }
        //target == 0, fill in 1's
        for (int i = 0; i <= len; i++) {
            table[i][0] = 1;
        }

        table[0][0] = 1;

        for (int i = 1; i <= len; i++) {
            for (int j = 1; j <= target; j++) {
                if (inputs[i-1] > j) {
                    table[i][j] = table[i-1][j];
                } else {
                    table[i][j] = table[i - 1][j] + table[i][j - inputs[i - 1]];
                }
            }
        }
        return table[len][target];
    }

dynamic programming method 2

public class DP {
    public int combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        if (target == 0) {
            return 0;
        }

        int[] table = new int[target + 1];
        table[0] = 1;

        for (int i = 0; i < candidates.length; i++) {
            for (int j = candidates[i]; j <= target; j++) {
                table[j] += table[j - candidates[i]];
            }
        }

        return table[target];
    }

    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        DP test = new DP();
        System.out.println(test.combinationSum(candidates, 7));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值