์ƒˆ์†Œ์‹

์•Œ๊ณ ๋ฆฌ์ฆ˜/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ”ผ๋กœ๋„ C++

  • -
728x90

 

1. ๋ฌธ์ œ

์ถœ์ฒ˜ : https://school.programmers.co.kr/learn/courses/30/lessons/87946

์œ ์ €์˜ ํ˜„์žฌ ํ”ผ๋กœ๋„ k์™€ ๊ฐ ๋˜์ „๋ณ„ "์ตœ์†Œ ํ•„์š” ํ”ผ๋กœ๋„", "์†Œ๋ชจ ํ”ผ๋กœ๋„"๊ฐ€ ๋‹ด๊ธด 2์ฐจ์› ๋ฐฐ์—ด dungeons ๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์œ ์ €๊ฐ€ ํƒํ—˜ํ• ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๋˜์ „ ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

2. ์ฝ”๋“œ

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

//์ˆ˜์—ด next_permutation์„ ํ™œ์šฉํ•˜์—ฌ์„œ ํ’€์ด
//๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ค ๊ณ„์‚ฐํ•œ ๋‹ค์Œ ์ฐจ๋ก€๋กœ ๊ฒ€์ฆํ•จ
int solution(int k, vector<vector<int>> dungeons) {
    int answer = 0;
    
    vector<int> v;
    // 0๋ถ€ํ„ฐ ๋˜์ „ ์‚ฌ์ด์ฆˆ๊นŒ์ง€ ๋ฒกํ„ฐ์— ์ €์žฅ
	for(int i=0; i<dungeons.size(); i++){
		v.push_back(i);
	}
    
    do{
        int pirodo=k;
        int count=0;
		for(int i=0; i<v.size(); i++){
            if(pirodo>=dungeons[v[i]][0]){
                //ํ”ผ๋กœ๋„ ์ฐจ๊ฐ ๋ฐ ๋˜์ „ ๊ฐฏ์ˆ˜ ์˜ฌ๋ฆฌ๊ธฐ
                count++;
                pirodo-=dungeons[v[i]][1];
            }
		}
        answer=max(answer,count);
	}while(next_permutation(v.begin(),v.end()));
    
    return answer;
}

 

3. ํ•ด์„ค

//์ˆ˜์—ด next_permutation์„ ํ™œ์šฉํ•˜์—ฌ์„œ ํ’€์ด
//๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ค ๊ณ„์‚ฐํ•œ ๋‹ค์Œ ์ฐจ๋ก€๋กœ ๊ฒ€์ฆํ•จ
int solution(int k, vector<vector<int>> dungeons) {
    int answer = 0;
    
    vector<int> v;
    // 0๋ถ€ํ„ฐ ๋˜์ „ ์‚ฌ์ด์ฆˆ๊นŒ์ง€ ๋ฒกํ„ฐ์— ์ €์žฅ
	for(int i=0; i<dungeons.size(); i++){
		v.push_back(i);
	}

 

๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๋งŽ์ง€ ์•Š๊ธฐ์— ์™„์ „ ํƒ์ƒ‰์„ ํ†ตํ•ด ํ’€์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ •ํ•ด์ง„ ๋ฐฐ์—ด์—์„œ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•  ๋•Œ๋Š” ์ˆ˜์—ด์„ ์‚ฌ์šฉํ•ด์„œ ๋งŒ๋“ค์–ด์ค€๋‹ค.

๋จผ์ € 0~ ๋˜์ „์˜ ๊ฐฏ์ˆ˜ ๊นŒ์ง€์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.

๋งŒ์•ฝ ๋˜์ „์˜ ๊ฐฏ์ˆ˜๊ฐ€ 3์ด๋ผ๋ฉด [0,1,2] ๊ฐ€ ๋งŒ๋“ค์–ด์ง„๋‹ค.

  do{
	int pirodo=k;
	int count=0;
	for(int i=0; i<v.size(); i++){
        	if(pirodo>=dungeons[v[i]][0]){
                //ํ”ผ๋กœ๋„ ์ฐจ๊ฐ ๋ฐ ๋˜์ „ ๊ฐฏ์ˆ˜ ์˜ฌ๋ฆฌ๊ธฐ
                count++;
                pirodo-=dungeons[v[i]][1];
            }
	}
    	answer=max(answer,count);
}while(next_permutation(v.begin(),v.end()));

๋งŒ๋“ค์–ด์ง„ ๋ฐฐ์—ด์„ ๊ฐ€์ง€๊ณ  next_permutation() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด์„œ ์ˆ˜์—ด์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

do while๋ฌธ์„ ํ†ตํ•ด ์ˆ˜์—ด์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ฐ›์•„์˜ฌ ๋•Œ ํ”ผ๋กœ๋„์™€ ๋˜์ „์ด ํ•„์š”ํ•œ ์ตœ์†Œ ํ”ผ๋กœ๋„๋ฅผ ๋„˜๊ธด๋‹ค๋ฉด ๋˜์ „์„ ํด๋ฆฌ์–ดํ•˜๋„๋ก ์„ค๊ณ„ํ•œ๋‹ค.

๋งŒ์•ฝ ์ตœ์†Œ ํ”ผ๋กœ๋„๋ฅผ ๋„˜๊ธฐ์ง€ ๋ชปํ•˜๋ฉด ๊ณ„์‚ฐํ•˜์ง€ ์•Š๊ณ  ๋„˜์–ด๊ฐ„๋‹ค.

๊ณ„์‚ฐ์ด ๋๋‚œ ํ›„ ๋งŒ์•ฝ Count๊ฐ€ ๊ธฐ์กด์˜ answer๋ณด๋‹ค ํด ๊ฒฝ์šฐ answer์— count ๊ฐ’์„ ์‚ฝ์ž…ํ•œ๋‹ค.

 

 

 

๋ฐ˜์‘ํ˜•
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.