zoukankan      html  css  js  c++  java
  • 组合总和Ⅳ

    Leetcode题目描述

    给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

    示例:

    nums = [1, 2, 3]
    target = 4
    
    所有可能的组合为:
    (1, 1, 1, 1)
    (1, 1, 2)
    (1, 2, 1)
    (1, 3)
    (2, 1, 1)
    (2, 2)
    (3, 1)
    

    请注意,顺序不同的序列被视作不同的组合。

    因此输出为 7。
    进阶:
    如果给定的数组中含有负数会怎么样?
    问题会产生什么变化?
    我们需要在题目中添加什么限制来允许负数的出现?

    致谢:
    特别感谢 @pbrother 添加此问题并创建所有测试用例。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum-iv
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    回溯超时代码

    可以解决部分问题,但是超时

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

    这道题,待做

  • 相关阅读:
    SQL序列键
    SQL日期跟时间值序列
    springboot日志配置
    weblogic10补丁升级与卸载
    idea使用svn报错
    mybatis插入数据并返回主键(oracle)
    UTF-8格式txt文件读取字节前三位问题
    https连接器
    git将本地项目上传码云
    aop的使用
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784994.html
Copyright © 2011-2022 走看看