题解 | 放苹果

放苹果

https://www.nowcoder.com/practice/bfd8234bb5e84be0b493656e390bdebf

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static List<Integer> path = new ArrayList<>();
    static List<List<Integer>> res = new ArrayList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();//苹果数
        int n = sc.nextInt();//盘子数
        if ( n > m) {
            n = m;
        }
        dfs(m, n, 0, 0);
        System.out.println(res.size());
    }

    private static void dfs(int apple, int bag, int sum, int start) {
        if (sum > apple || path.size() > bag) {
            return;
        }
        if (sum == apple && path.size() == bag) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i <= apple; i++) {
            path.add(i);
            dfs(apple, bag, sum + i, i );
            path.remove(path.size() - 1);
        }
    }
}

盘子比苹果多 那么剩下的空盘和可以添加到任意一种组合

#为了找工作你投递了多少公司?#
全部评论

相关推荐

点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务