๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (๊ฐ€์žฅ ํฐ ์ˆ˜, ์ •๋ ฌ) C++

by UKHYUN22 2022. 1. 4.
728x90

 

์ผ๋‹จ ์ˆœ์—ด๋กœ ์ ‘๊ทผ์„ ํ–ˆ๋Š”๋ฐ ๋ช‡ ๊ฐœ์˜ Test case๊ฐ€ ๋Œ์•„๊ฐ€์ง€ ์•Š์•„์„œ ์ข€ ๋‹ต๋‹ตํ–ˆ๋‹ค. Sort๋ฅผ ํ•  ๋•Œ ๋น„๊ต ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋ถ€์—ฌํ•˜๋‹ˆ๊นŒ ๋ฐ”๋กœ ํ’€๋ ธ๋˜ ๋ฌธ์ œ

 

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

using namespace std;

bool cmp(const string& a, const string& b) {
    if(a + b > b + a) return true;
    else return false;
}

string solution(vector<int> numbers) {
    string answer = "";
    vector<string> real;
    
    // ๋ฒกํ„ฐ์— string์œผ๋กœ ํ• ๋‹น
    for(int i = 0 ; i < numbers.size() ; i++) {
        real.push_back(to_string(numbers[i]));
    }
    
    // ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ˆซ์ž๋ฅผ ์ •๋ ฌ
    sort(real.begin(), real.end(), cmp);
    
    // answer ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค์–ด์คŒ
    for(int i = 0 ; i < real.size() ; i++) {
        answer += real[i];
    }
    
    if(answer[0] == '0')
        return "0";
    else
        return answer;
}

 

 

next_permutation์„ ์‚ฌ์šฉํ•ด์„œ ํ’€์–ด๋ดค๋˜ ๋ฌธ์ œ

 

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

using namespace std;

string solution(vector<int> numbers) {
    string answer = "";
    string real = "";
    int max = 0;
    
    // ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ˆซ์ž๋ฅผ ์ •๋ ฌ
    sort(numbers.begin(), numbers.end());
    
    // ์ˆœ์—ด์กฐํ•ฉ์„ ์ด์šฉ
    do {
        // ๊ฐ ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•ด์„œ answer์— ๋‹ด์•„์ฃผ๊ธฐ
        for(int i = 0 ; i < numbers.size() ; i++) 
            answer += to_string(numbers[i]);
        
        // answer๊ฐ€ ์ตœ๋Œ“๊ฐ’์ธ ๊ฒฝ์šฐ ๊ณ„์† ์ตœ์‹ ํ™”์‹œ์ผœ์ค€๋‹ค.
        if(max < stoi(answer))
            max = stoi(answer);
        
        // answer ์ดˆ๊ธฐํ™”
        answer = "";
    } while(next_permutation(numbers.begin(), numbers.end()));
    
    real = to_string(max);
    
    if(real[0] == '0') return "0";
    else
        return real;
}