【问题标题】:Integer partition in java store output in an arrayjava中的整数分区将输出存储在数组中
【发布时间】:2017-10-28 21:08:43
【问题描述】:

我有来自Print all unique integer partitions given an integer as input的以下代码

void printPartitions(int target, int maxValue, String suffix) {
    if (target == 0)
        System.out.println(suffix);
    else {
        if (maxValue > 1)
            printPartitions(target, maxValue-1, suffix);
        if (maxValue <= target)
            printPartitions(target-maxValue, maxValue, maxValue + " " + suffix);
    }
}

当它调用printPartitions(4, 4, ""); 时,它会给出以下输出:

1 1 1 1 
1 1 2 
2 2 
1 3 
4 

我怎样才能得到这样的数组中的输出:

[[1,1,1,1],[1,1,2],[2,2],[1,3],[4]]

【问题讨论】:

    标签: java


    【解决方案1】:

    在这种情况下,您应该将值收集到一个数组中。我已经用列表替换了数组,以简化“添加”操作(对于您应该维护索引的数组):

    void printPartitions(int target, int maxValue, List<String> suffix, List<List<String>> list) {
        if (target == 0) {
            list.add(suffix);
        } else {
            if (maxValue > 1)
                printPartitions(target, maxValue-1, suffix, list);
            if (maxValue <= target) {
                List<String> tmp = new ArrayList<String>();
                tmp.add(0, String.valueOf(maxValue));
                tmp.addAll(suffix);
                printPartitions(target-maxValue, maxValue, tmp, list);
            }
        }
    }
    
    void callPrintPartitions() {
        List<List<String>> list = new ArrayList<List<String>>();
        printPartitions(4, 4, new ArrayList<String>(), list);
        System.out.println(list);
    }
    

    输出:

    [[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-31
      • 2014-09-13
      • 2016-12-08
      • 2018-08-25
      • 1970-01-01
      • 2015-03-07
      • 2017-09-20
      • 2012-10-12
      相关资源
      最近更新 更多