View

๋ฐ˜์‘ํ˜•

1182๋ฒˆ: ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ

๋ฌธ์ œ

N๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ด ์žˆ์„ ๋•Œ, ํฌ๊ธฐ๊ฐ€ ์–‘์ˆ˜์ธ ๋ถ€๋ถ„์ˆ˜์—ด ์ค‘์—์„œ ๊ทธ ์ˆ˜์—ด์˜ ์›์†Œ๋ฅผ ๋‹ค ๋”ํ•œ ๊ฐ’์ด S๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” N๊ณผ ์ •์ˆ˜ S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 โ‰ค N โ‰ค 20, |S| โ‰ค 1,000,000) ๋‘˜์งธ ์ค„์— N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ์ ˆ๋Œ“๊ฐ’์€ 100,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ํ•ฉ์ด S๊ฐ€ ๋˜๋Š” ๋ถ€๋ถ„์ˆ˜์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

์˜ˆ์ œ ์ž…๋ ฅ 1

5 0
-7 -3 -2 5 8

์˜ˆ์ œ ์ถœ๋ ฅ 1

1

S๊ฐ€ 0์ผ๋•Œ๋Š” sum=0์˜ ์ดˆ๊ธฐํ™”์™€ ๊ฒน์น˜๋ฏ€๋กœ ์‹ ๊ฒฝ์จ์ค˜์•ผํ•œ๋‹ค

๋ถ€๋ถ„์ง‘ํ•ฉ์œผ๋กœ ํ’€๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์Œ


๐Ÿคฆโ€โ™€๏ธ My Solution

package ์ˆœ์—ด์กฐํ•ฉ;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BJ_9095 {

    static int N, S, total;
    static int arr[];
    static boolean select[];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        S = Integer.parseInt(st.nextToken());
        arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());

        }

        total = 0;
        select = new boolean[N];
        subset(0);
        if (S == 0)
            total -= 1;
        System.out.println(total);

    }

    static public void subset(int idx) {
        // ๊ธฐ์ € ์กฐ๊ฑด
        int sum = 0;
        if (idx == N) {
            sum = 0;
            for (int i = 0; i < N; i++) {
                if (select[i]) {

                    sum += arr[i];
                }
            }

            if (sum == S)
                total++;

            return;
        }

        select[idx] = true;
        subset(idx + 1);

        select[idx] = false;
        subset(idx + 1);
    }

}

๋ฐ˜์‘ํ˜•
Share Link
reply
๋ฐ˜์‘ํ˜•
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
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 27 28 29 30