๐Ÿ’ป

[๋ฐฑ์ค€] ๋ฐฑํŠธ๋ž˜ํ‚น - 1182. ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œํ’€์ด Baekjoon

[๋ฐฑ์ค€] ๋ฐฑํŠธ๋ž˜ํ‚น - 1182. ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ

๋˜ํšจ๋‹ˆ 2020. 2. 21. 23:51

๋ฌธ์ œ

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

 

์ƒ๊ฐ

์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ๋Š” n์ด 20๊นŒ์ง€์ด๋ฏ€๋กœ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ํ’€๋ฉด ๋  ๊ฒƒ ๊ฐ™์•˜๋‹ค. 

 

์žฌ๊ท€ํ˜ธ์ถœ๋˜๋Š” ๊ณผ์ •์„ ๊ตฌํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. 

์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ, ํ•ด๋‹น ์›์†Œ๋ฅผ sum์— ๋”ํ•˜๊ฑฐ๋‚˜ ํ˜น์€ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ์ด๋ฏ€๋กœ ํ˜ธ์ถœํ• ๋•Œ๋งˆ๋‹ค 2๋ฐฐ์”ฉ ์ฆ๊ฐ€ํ•œ๋‹ค. 

 

find(0, 0)

1) ์ฒซ๋ฒˆ์งธ ์ •์ˆ˜์ธ -7์„ ๋”ํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜

-> find(1, -7) , find(1, 0)

2) ๋‘๋ฒˆ์งธ ์ •์ˆ˜์ธ -3์„ ๋”ํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜

-> find(2, -10), find(2, -7) , find(2, -3), find(2, 0)

3) ์„ธ๋ฒˆ์งธ ์ •์ˆ˜์ธ -2๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜

-> find(3, -12), find(3, -10) / find(3, -9), find(3, -7),

find(3, -5), find(3, -3) / find(3,  -2), find(3, 0)

4) ๋„ค๋ฒˆ์งธ ์ •์ˆ˜์ธ -5๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜

-> find(4, -7), find(4, -12), find(4, -5), find(4, -10) / find(4, -4),  find(4, -9), find(4, -5), find(4, -7),

find(4, 0), find(4, -5), find(4, 2), find(4, -3)/ find(4, 3), find(4, -2), find(4,5), find(4, 0)

5) ๋‹ค์„ฏ๋ฒˆ์งธ ์ •์ˆ˜์ธ 8์„ ๋”ํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜

-> find(5, -1), find(5, -7), find(5, 4), find(5, -12), find(5, 3), find(5, -5), find(5, -2), find(5, -10) / find(5, 4), find(5, -4), find(5, -1),

find(5, -9), find(5, 3), find(5, -5), find(5, 1), find(5, -7),

find(5, 8), find(5, 0), find(5, 3), find(5, -5), find(5, 10), find(5, 2), find(5, 5), find(5, -2) / find(5, 11), find(5, 3), find(5, 6), find(5, -2), find(5, 13), find(5, 5), find(5, 5), find(5, 0)

 

์ž‘์„ฑํ•œ ์ฝ”๋“œ

#include <iostream>

using namespace std;

int n,s;
int arr[21];
int cnt=0;
void find(int index, int sum){
    if(n==index){
        if(sum==s){
            cnt ++;
        }
        return;
    }
    find(index+1, sum+arr[index]); 
    find(index+1, sum);
}
int main(int argc, const char * argv[]) {
    // insert code here...
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    cin >> n >> s;
    
    for(int i=0; i<n; i++){
        cin >> arr[i];
    }
    find(0, 0);
    if(s==0){ //s๊ฐ€ 0์ผ ๊ฒฝ์šฐ, ๊ณต์ง‘ํ•ฉ์— ๋Œ€ํ•ด cnt๊ฐ’์ด 1์ด ์ถ”๊ฐ€๋˜๊ธฐ๋•Œ๋ฌธ์— ๋นผ์ค˜์•ผํ•œ๋‹ค.
        cnt += -1;
    }
    cout << cnt << "\n";
    return 0;
}

๋ฐ˜์‘ํ˜•
Comments