给出N个正整数组成的数组A,求能否从中选出若干个,使他们的和为K。如果可以,输出:"YES",否则输出"NO"。用Java实现

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int num[] = new int[1000];
        int N, K;
        Scanner scanner = new Scanner(System.in);
        N = scanner.nextInt();
        K = scanner.nextInt();
        for (int i = 0; i < N; i++) {
            num[i] = scanner.nextInt();
        }
        System.out.println(judge(num, N, K));
    }

    private static String judge(int[] num, int n, int k) {
        int flag = 0; // 用来游标值  如果前面的值大于直接跳过
        while (flag < n && num[flag] != num[n]) {
            int sum = 0;
            int flag_2 = flag;
            // 判断和是否小余k如果和大于直接跳过  加上临界值的判断
            while (sum <= k && num[flag_2] != num[n+1]) {
                sum += num[flag_2];
                if (sum == k){
                    return "YES";
                }
                flag_2++;
            }
            flag++;
        }
        return "NO";
    }
} 

 

posted on 2019-04-12 10:46  蔚蓝色の天空  阅读(1164)  评论(0编辑  收藏  举报