华为机试--吃夜宵

方法:dp

就是输入两个整数m,x;x是总价,m是个数

第二行输入m个价格,问你m个价格中有几种方案相加等于x。

比如x=25,m=5, 第二行是:3,7,5,5,10,答案是两种,因为3+7+10=20,两个5算两种不同的方案


// We have imported the necessary tool classes.
// If you need to import additional packages or classes, please import here.

public class Main {
    public static void main(String[] args) {
    // please define the JAVA input here. For example: Scanner s = new Scanner(System.in);
        Scanner sc = new Scanner(System.in);
        int all = sc.nextInt(); //总价
        int cnt = sc.nextInt(); //个数
        int arr[] = new int[cnt];
        for(int i = 0; i < cnt; i++)
            arr[i] = sc.nextInt();
    // please finish the function body here.
        int dp[] = new int[all + 1];
        dp[0] = 1;
        for(int i = 0; i < cnt; i++){
            for(int j = all; j >= arr[i]; j--)
                dp[j] = dp[j] + dp[j - arr[i]];
        }
    // please define the JAVA output here. For example: System.out.println(s.nextInt());
        System.out.println(dp[all] != 0 ? dp[all] : -1);
    }
}

全部评论

相关推荐

07-21 12:41
已编辑
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
评论
2
7
分享

创作者周榜

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