[Programmers] Lv2. ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ํ•ฉ์˜ ๊ฐœ์ˆ˜ | C++

2023. 6. 14. 02:28ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์ค‘๋ณต์—†์ด ์ €์žฅ์„ ํ•ด์•ผ ํ•˜๋‹ˆ, set์— ์ €์žฅํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์—ฐ์† ์ˆ˜์—ด ํ•ฉ๊ณ„๋ฅผ ๊ตฌํ•˜๋Š” ๋ถ€๋ถ„์—์„  deque๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. ์ธ๋ฑ์‹ฑ์ด ๊ฐ€๋Šฅํ•˜๊ณ , ๋งจ ์•ž ๋งจ ๋’ค ์‚ฝ์ž… ์‚ญ์ œ๊ฐ€ ํšจ์œจ์ ์ธ deque๋ผ๋ฉด ์ข‹์€ ํšจ์œจ์„ ๋‚ผ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

1. vector์— ์ €์žฅ๋˜์–ด ์žˆ๋˜ elements์˜ ์›์†Œ๋“ค์„ ๋ชจ์กฐ๋ฆฌ deque๋กœ ์˜ฎ๊ฒจ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

2. 0๋ฒˆ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ถ”์ถœํ•  ๊ฐœ์ˆ˜ (1 ~ element.size()) ์ธ๋ฑ์Šค๋งŒํผ์˜ ํ•ฉ๊ณ„๋ฅผ ๊ตฌํ•ฉ๋‹ˆ๋‹ค.

    - ํ•ฉ๊ณ„๋ฅผ set์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

    - deque์˜ ๋งจ ์•ž ์›์†Œ๋ฅผ ๋งจ ๋’ค๋กœ ๋ณด๋ƒ…๋‹ˆ๋‹ค.

    - deque์˜ ์›์†Œ์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

 

 

์œ„ ์˜ˆ์ œ๋ฅผ ์˜ˆ๋กœ ๋“ค๋ฉด, [7, 9, 1, 1, 4]์—์„œ ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ๊ธธ์ด๊ฐ€ 2์ธ ๊ฒƒ์„ ๋งŒ๋“ ๋‹ค๊ณ  ํ•˜์˜€์„ ๋•Œ,

#1
7 9 1 1 4
// 7 + 9 = 16  -> set์— ์ €์žฅ
// 7์€ ๋งจ ๋’ค๋กœ ๋ณด๋ƒ„

#2
9 1 1 4 7
// 9 + 1 = 10  -> set์— ์ €์žฅ
// 9๋Š” ๋งจ ๋’ค๋กœ ๋ณด๋ƒ„

...


#5
4 7 9 1 1
// 4 + 7 = 11  -> set์— ์ €์žฅ
// 4๋Š” ๋งจ ๋’ค๋กœ ๋ณด๋ƒ„  -> 7 9 1 1 4๋กœ ์›๋ž˜๋Œ€๋กœ ๋Œ์•„์˜ด -> ๋ฃจํ”„ ๋

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <set>
#include <deque>
#include <vector>
using namespace std;


int Sum(const deque<int>& myDeque, int selection) {
    int sum = 0;
 
    for (int i = 0; i < selection; i++)
        sum += myDeque[i];
    return sum;
}

deque<int> MigrationToDeque(const vector<int>& elements) {
    deque<int> result(elements.size());

    for (int i = 0; i < result.size(); i++)
        result[i] = elements[i];
    return result;
}

int solution(vector<int> elements) {
    deque<int> myDeque = MigrationToDeque(elements);
    set<int> answers;

    for (int selection = 1; selection < myDeque.size(); selection++) {
        for (int start = 0; start < myDeque.size(); start++) {
            int sum = Sum(myDeque, selection);
            answers.insert(sum);
            
            int front = myDeque.front();
            myDeque.push_back(front);
            myDeque.pop_front();
        }
    }

    int sum = Sum(myDeque, myDeque.size());      // ์ „๋ถ€ ์„ ํƒํ•˜๋Š” ๊ฒƒ์€ ๋ฐ”๊ฟ”๊ฐ€๋ฉฐ ํ•ด๋„ ๊ฐ’์ด ๋˜‘๊ฐ™์œผ๋ฏ€๋กœ ํ•œ ๋ฒˆ๋งŒ ์ˆ˜ํ–‰
    answers.insert(sum);
    return answers.size();
}

 

 

 

728x90
๋ฐ˜์‘ํ˜•