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

找出可能的合的组合

淙嶙5年前 (2020-07-21)未命名1241

描述


给出一组不重复的正整数,从这组数中找出所有可能的组合使其加合等于一个目标正整数 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;
    }

相关文章

BootstrapDialog的简单封装

BootstrapDialog的简单封装

类似alert的提示弹出框$.dialogShow = function (msg,callBack,title) {   if(typeo...

...

bootstrapTable使用点小结

bootstrapTable使用点小结

1.获取选中行的index索引号 //借鉴而来 function getIdSelections() { return $.map($("#tb_data").bootstrapTable('get...

发表评论

访客

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