• 377. Combination Sum IV


    Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

    Example:

    nums = [1, 2, 3]
    target = 4
    
    The possible combination ways are:
    (1, 1, 1, 1)
    (1, 1, 2)
    (1, 2, 1)
    (1, 3)
    (2, 1, 1)
    (2, 2)
    (3, 1)
    
    Note that different sequences are counted as different combinations.
    
    Therefore the output is 7.
    

    Follow up:
    What if negative numbers are allowed in the given array?
    How does it change the problem?
    What limitation we need to add to the question to allow negative numbers?

    Credits:
    Special thanks to @pbrother for adding this problem and creating all test cases.

    class Solution {
        public int combinationSum4(int[] nums, int target) {
            int[] res = new int[1];
            help(res, new ArrayList(), nums, target, 0);
            return res[0];
        }
        public void help(int[] res, List<Integer> cur, int[] nums, int target, int sum) {
            if(sum > target) return;
            if(sum == target) {
                res[0]++;
                return;
            }
            
            for(int i = 0; i < nums.length; i++) {
                sum += nums[i];
                cur.add(nums[i]);
                help(res, cur, nums, target, sum);
                sum -= nums[i];
                cur.remove(cur.size() - 1);
            }
        }
    }

    TLE了,屮

    class Solution {
        public int combinationSum4(int[] nums, int target) {
            if (target == 0) {
                return 1;
            }
            int res = 0;
            for (int i = 0; i < nums.length; i++) {
                if (target >= nums[i]) {
                    res += combinationSum4(nums, target - nums[i]);
                }
            }
            return res;
        }
    }

    这个也是递归,也tle了。

    仔细看一下,和coin change2十分相似,都是从中间态得到最终结果,那就是个dp,还是初始化dp【0】 = 1

    class Solution {
        public int combinationSum4(int[] nums, int target) {
            int[] comb = new int[target + 1];
            comb[0] = 1;
            for (int i = 1; i < comb.length; i++) {
                for (int j = 0; j < nums.length; j++) {
                    if (i - nums[j] >= 0) {
                        comb[i] += comb[i - nums[j]];
                    }
                }
            }
            return comb[target];
        }
    }

    看清楚需求,这个包括了重复的,所以coin在inner loop

  • 相关阅读:
    Java 的this和super关键字
    Java关于访问控制权限
    Java 封装 继承 多态
    Java的集成开发工具
    如何查询小程序中的代码量
    小程序中使用echarts及使用的坑
    微信小程序-新的页面授权机制
    前端处理几十万条数据不卡顿(window.requestAnimationFrame)
    Vs code中Eslint 与 Prettier格式化冲突
    从原型与原型链的角度看es6 class
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13611868.html
Copyright © 2020-2023  润新知