当前位置:首页 > 未命名 > 正文内容

找出可能的合的组合

淙嶙6年前 (2020-07-21)未命名1535

描述


给出一组不重复的正整数,从这组数中找出所有可能的组合使其加合等于一个目标正整数 N,如:

一组数为 1, 2, 3,目标数为 4,那么可能的加合组合为:
1, 1, 1, 1
1, 1, 2
1, 2, 1
1, 3
2, 1, 1
2, 2
3, 1
注意相同的组合数字顺序不同也算一种,所以这个例子的结果是 7 种。


输入


一组不重复的正整数(, 隔开)以及目标正整数(与数组用空格隔开)


输出


所有可能的加合等于目标正整数 N 的组合种数


输入样例

1,2,3 4

输出样例

7

private static String solution(String line) {
    // 在此处理单行数据
   String[] parts = line.split(" ");
        String[] src = parts[0].split(",");
        int[] arr = new int[src.length];
        for (int i = 0; i < src.length; ++i) {
            arr[i] = Integer.parseInt(src[i]);
        }
        int result = fun(arr,Integer.parseInt(parts[1]));
        return String.valueOf(result);
    }
    public static int fun(int[] arr,int t) {
    int count = 0;
        for (int a : arr) {
            if (t == a) {
            count ++;
            } else if (t > a) {
            count += fun(arr,t - a);
            }
        }
        return count;
    }

相关文章

Ubuntu安装docker

Ubuntu安装docker

1.查看ubuntu版本,官方指定的版本才能安装。https://docs.docker.com/install/linux/docker-ce/ubuntu/To install Docker CE...

关于我

关于我

人的学习能力是随着努力程度变化的,毅力才是打开成功大门的钥匙 错在止步不前,胜在改变自己 The mistake is to stop, the better is to change yo...

Dubbo的依赖(二)

Dubbo的依赖(二)

dubbo官网文档:http://dubbo.apache.org/#/docs/dependencies.md?lang=zh-cn转自动dubbo官方文档依赖必须依赖JDK 1.6+ [...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。