Comment detail

自然数の分割 (Nested Flatten)

普通に再帰で。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.*;
public class PartNumber {
    public static void main(String[] args) {
        System.out.println(part(5, 3));    // => [[5, 0, 0], [4, 1, 0], ..., [0, 1, 4], [0, 0, 5]]
    }
    private static List<List<Integer>> part(int n, int m) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> item;
        if (m == 1) {
            item = new ArrayList<Integer>();
            item.add(n);
            res.add(item);
            return res;
        }
        for (int i = n; i >= 0; i--) {
            List<List<Integer>> r = part(n - i, m - 1);
            for (List<Integer> l : r) {
                item = new ArrayList<Integer>();
                item.add(i);
                item.addAll(l);
                res.add(item);
            }
        }
        return res;
    }
}

Index

Feed

Other

Link

Pathtraq

loading...