k个正整数(可重复)之和为n,求所有可能路径

 1 import java.util.ArrayDeque;
 2 import java.util.ArrayList;
 3 import java.util.Deque;
 4 import java.util.List;
 5 
 6 public class Solution {
 7     public void dp(int k, int n, List> result, Deque curr) {
 8         if (k > n || (k == 0 && n != 0)) {
 9             return;
10         }
11         if (k == 0 && n == 0) {
12             result.add(new ArrayList<>(curr));
13             return;
14         }
15 
16         for (int i = 1; i <= n; i++) {
17             curr.addLast(i);
18             dp(k - 1, n - i, result, curr);
19             curr.removeLast();
20 
21         }
22     }
23 
24     public List> so(int k, int n) {
25         List> result = new ArrayList<>();
26         Deque curr = new ArrayDeque<>();
27         dp(k, n, result, curr);
28         return result;
29     }
30 
31     public static void main(String[] args) {
32         Solution solution = new Solution();
33         solution.so(3, 5);
34     }
35 
36 }

 

你可能感兴趣的:(k个正整数(可重复)之和为n,求所有可能路径)