본문 바로가기

알고리즘119

[프로그래머스] 모음사전 c++ 풀이 백트래킹을 이용해 풀었다. 사용했던 원소를 계속 사용할 수 있기 때문에 chk배열을사용하지 않고 풀었다. #include #include using namespace std; string end_s; int chk[5]; string alphabet = "AEIOU"; int answer ; int cnt; void dfs(string s){ //원하는 단어가 있다면 리턴한다. if(s==end_s) { answer=cnt; return; } //길이가 5이하인 단어를 만든다. if(s.size()>4) return; for(int i=0;i 2024. 1. 22.
[프로그래머스] 피로도 c++ 풀이 카테고리가 완전탐색이기도 하지만 던젼길이가 최대 8이기 때문에 완전탐색으로 풀어도 된다고 생각했다. 백트래킹을 이용해서 던전을 방문하는 순서를 모두 탐색한다. 던젼을 선택할때 남은 피로도로 탐색할수있는지 검사한다. 스코어가 0보다 작다면 더이상 탐색못하므로 return해준다. #include #include using namespace std; vector dungeon; vectorchk; int answer; void dfs(int score,int cnt){ //남은 피로도가 없음녀 탐색 끝 if(scoreanswer) answer=cnt; for(int i=0;i 2024. 1. 22.
[프로그래머스] 카펫 c++ 풀이 노란색의 가로길이가 i라고 한다면 i+2는 전체가로길이다. 전체가로길이로 크기를 나눴을때 나머지가 발생한다면 continue를 해준다. 1.노란색의 크기를 i(노란색의 가로길이)로 나누었을때 나머지가 생기지 않고 , 2.노란색의 세로길이(yellow/i)가 갈색의 세로길이-2랑 같을때 i가 노란색의 가로길이이다. #include #include using namespace std; vector solution(int brown, int yellow) { vector answer; int total = brown + yellow; for(int i =1 ;i*i 2024. 1. 22.
[프로그래머스] 소수찾기 c++ 풀이 1. 소수가 나올 가능성이 있는 크기만큼 소수를 체크할수있는 배열 p_num을 만든다. 2. 백트래킹을 활용해서 나올수 있는 모든 숫자들을 만들고 소수인지 체크한다. 3. 소수의 중복제거를 위해 set을 활용해 소수개수를 세어준다. #include #include #include #include using namespace std; string number; vectorchk; vector p_num; set make_n; void dfs(int index, string s){ if(index>0){ if(!p_num[stoi(s)]){ make_n.insert(stoi(s)); } } for(int i =0 ;i 2024. 1. 22.