[C++] 동적 κ³„νšλ²•(Dynamic Programming)

2020. 4. 30. 19:18Β·πŸ“ Computer Science/✏ Algorithm

동적 κ³„νšλ²•(Dynamic Programming)

λ³΅μž‘ν•œ 문제λ₯Ό κ°„λ‹¨ν•œ μ—¬λŸ¬ 개의 문제둜 λ‚˜λˆ„μ–΄ ν‘ΈλŠ” 방법이닀.

  • λ˜‘κ°™μ€ 연산을 λ°˜λ³΅ν•˜μ§€ μ•Šλ„λ‘ λ§Œλ“€μ–΄ μ£Όκ³  μ‹€ν–‰ μ‹œκ°„μ„ 쀄일 수 μžˆλ‹€.
  • μž‘μ€ λ¬Έμ œλ“€μ„ ν’€μ–΄λ‚˜κ°€λ‹€ 보면 이전에 ꡬ해둔 더 μž‘μ€ λ¬Έμ œλ“€μ΄ ν™œμš©λ˜λŠ” 것을 ν™•μΈν•˜κ²Œ λœλ‹€. 이에 λŒ€ν•œ κ·œμΉ™μ„ μ°Ύμ•˜μ„ λ•Œ 점화식을 λ„μΆœν•΄ λ‚΄μ–΄ 동적 κ³„νšλ²•μ— μ μš©ν•œλ‹€.

 

풀이법

  1. dp[i]κ°€ μ˜λ―Έν•˜λŠ” λ°”
  2. dp[i]λ₯Ό initialize ν•˜λŠ” 방법
  3. dp[i]의 점화식
  4. dp[i]λ₯Ό μ±„μš°λŠ” μˆœμ„œ
  5. 정닡이 μ˜λ―Έν•˜λŠ” λ°”

 

https://jyeonth.tistory.com/7

 

Leetcode: Word Break

Word Break I Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused mul

jyeonth.tistory.com

 

문제

https://www.acmicpc.net/problem/1932

 

1932번: μ •μˆ˜ μ‚Όκ°ν˜•

문제 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 μœ„ 그림은 크기가 5인 μ •μˆ˜ μ‚Όκ°ν˜•μ˜ ν•œ λͺ¨μŠ΅μ΄λ‹€. 맨 μœ„μΈ΅ 7λΆ€ν„° μ‹œμž‘ν•΄μ„œ μ•„λž˜μ— μžˆλŠ” 수 쀑 ν•˜λ‚˜λ₯Ό μ„ νƒν•˜μ—¬ μ•„λž˜μΈ΅μœΌλ‘œ λ‚΄λ €μ˜¬ λ•Œ, μ΄μ œκΉŒμ§€ μ„ νƒλœ 수의 합이 졜�

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[501][501];

int main()
{
	int n;
	cin >> n;

	int result = 0;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= i; j++) {
			cin >> dp[i][j];
			if (j == 1) // μ™Όμͺ½ λŒ€κ°μ„ 
				dp[i][j] += dp[i - 1][j];
			else if (i == j) // 였λ₯Έμͺ½ λŒ€κ°μ„ 
				dp[i][j] += dp[i - 1][j - 1];
			else
				dp[i][j] += max(dp[i - 1][j], dp[i - 1][j - 1]);

			if (result < dp[i][j])
				result = dp[i][j];
		}
        
	cout << result;
}

 

https://www.acmicpc.net/problem/1463

 

1463번: 1둜 λ§Œλ“€κΈ°

첫째 쀄에 1보닀 ν¬κ±°λ‚˜ κ°™κ³ , 106보닀 μž‘κ±°λ‚˜ 같은 μ •μˆ˜ N이 μ£Όμ–΄μ§„λ‹€.

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[1000001];

int main()
{
	int n;
	cin >> n;

	dp[1] = 0;
	for (int i = 2; i <= n; i++)	{
		dp[i] = dp[i - 1] + 1;
		if (i % 2 == 0 && dp[i / 2] + 1 <= dp[i])
			dp[i] = dp[i / 2] + 1;
		if (i % 3 == 0 && dp[i / 3] + 1 <= dp[i])
			dp[i] = dp[i / 3] + 1;
	}

	cout << dp[n];
}

 

https://www.acmicpc.net/problem/1912

 

1912번: 연속합

첫째 쀄에 μ •μˆ˜ n(1 ≤ n ≤ 100,000)이 μ£Όμ–΄μ§€κ³  λ‘˜μ§Έ μ€„μ—λŠ” n개의 μ •μˆ˜λ‘œ 이루어진 μˆ˜μ—΄μ΄ μ£Όμ–΄μ§„λ‹€. μˆ˜λŠ” -1,000보닀 ν¬κ±°λ‚˜ κ°™κ³ , 1,000보닀 μž‘κ±°λ‚˜ 같은 μ •μˆ˜μ΄λ‹€.

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[100001];

int main()
{
	int n;
	cin >> n >> dp[0];
	for (int i = 1; i < n; ++i) {
		cin >> dp[i];
		dp[i] = max(dp[i], dp[i - 1] + dp[i]);
	}

	cout << *max_element(dp, dp + n);
}

 

https://leetcode.com/problems/longest-valid-parentheses/

 

Longest Valid Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

#include <vector>
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
    int longestValidParentheses(string s) {
        int answer = 0;
        stack<int> st;
        vector<int> dp(s.size(), 0);

        for (int i = 0; i < s.size(); i++) {
            char c = s[i];
            if (c == '(')
                st.push(i);
            else {
                if (st.empty())
                    continue;

                int index = st.top();
                st.pop();
                dp[i] = i - index + 1 + (index > 0 ? dp[index - 1] : 0);
            }
            answer = max(answer, dp[i]);
        }

        return answer;
    }
};

 

문제 : 연속 값이 λΆˆκ°€λŠ₯ν•  λ•Œ μ΅œλŒ“κ°’ κ΅¬ν•˜κΈ°

https://www.acmicpc.net/problem/2579

 

2579번: 계단 였λ₯΄κΈ°

계단 였λ₯΄κΈ° κ²Œμž„μ€ 계단 μ•„λž˜ μ‹œμž‘μ λΆ€ν„° 계단 κΌ­λŒ€κΈ°μ— μœ„μΉ˜ν•œ λ„μ°©μ κΉŒμ§€ κ°€λŠ” κ²Œμž„μ΄λ‹€. <κ·Έλ¦Ό 1>κ³Ό 같이 각각의 κ³„λ‹¨μ—λŠ” μΌμ •ν•œ μ μˆ˜κ°€ μ“°μ—¬ μžˆλŠ”λ° 계단을 밟으면 κ·Έ 계단에 μ“°μ—¬ μžˆλŠ” 점

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n;
	cin >> n;

	int stair[300], dp[300];
	for (int i = 0; i < n; i++)
		cin >> stair[i];

	dp[0] = stair[0];
	dp[1] = stair[0] + stair[1];
	dp[2] = max(stair[1] + stair[2], stair[0] + stair[2]);
	for (int i = 3; i < n; i++)
		dp[i] = max(stair[i] + dp[i - 2], stair[i] + stair[i - 1] + dp[i - 3]);

	cout << dp[n - 1];
}

 

https://www.acmicpc.net/problem/2156

 

2156번: 포도주 μ‹œμ‹

νš¨μ£ΌλŠ” 포도주 μ‹œμ‹νšŒμ— κ°”λ‹€. κ·Έ 곳에 κ°”λ”λ‹ˆ, ν…Œμ΄λΈ” μœ„μ— λ‹€μ–‘ν•œ 포도주가 λ“€μ–΄μžˆλŠ” 포도주 μž”μ΄ 일렬둜 놓여 μžˆμ—ˆλ‹€. νš¨μ£ΌλŠ” 포도주 μ‹œμ‹μ„ ν•˜λ €κ³  ν•˜λŠ”λ°, μ—¬κΈ°μ—λŠ” λ‹€μŒκ³Ό 같은 두 κ°€μ§€ 규

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n;
	cin >> n;

	int grape[10001];
	for (int i = 1; i <= n; ++i)
		cin >> grape[i];

	int dp[10001]{};
	dp[1] = grape[1];
	dp[2] = grape[1] + grape[2];
	for (int i = 3; i <= n; ++i)
		dp[i] = max(dp[i - 1], max(dp[i - 2], dp[i - 3] + grape[i - 1]) + grape[i]);

	cout << dp[n];
}

 

문제 : LIS(졜μž₯ 증가 λΆ€λΆ„ μˆ˜μ—΄)

https://www.acmicpc.net/problem/11053

 

11053번: κ°€μž₯ κΈ΄ μ¦κ°€ν•˜λŠ” λΆ€λΆ„ μˆ˜μ—΄

μˆ˜μ—΄ Aκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, κ°€μž₯ κΈ΄ μ¦κ°€ν•˜λŠ” λΆ€λΆ„ μˆ˜μ—΄μ„ κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€. 예λ₯Ό λ“€μ–΄, μˆ˜μ—΄ A = {10, 20, 10, 30, 20, 50} 인 κ²½μš°μ— κ°€μž₯ κΈ΄ μ¦κ°€ν•˜λŠ” λΆ€λΆ„ μˆ˜μ—΄μ€ A = {10, 20, 10, 30, 20, 50} 이

www.acmicpc.net

#include <iostream>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int N, ans = 0;
	cin >> N;

	int A[1010]{}, dp[1010]{};
	for (int i = 1; i <= N; i++)
		cin >> A[i];

	for (int i = 1; i <= N; i++) {
		for (int j = 1; j < i; j++)
			if (A[i] > A[j] && dp[i] < dp[j])
				dp[i] = dp[j];
		dp[i]++;
		if (ans < dp[i])
			ans = dp[i];
	}
	cout << ans;
}

 

https://www.acmicpc.net/problem/2565

 

2565번: 전깃쀄

첫째 μ€„μ—λŠ” 두 μ „λ΄‡λŒ€ μ‚¬μ΄μ˜ μ „κΉƒμ€„μ˜ κ°œμˆ˜κ°€ μ£Όμ–΄μ§„λ‹€. μ „κΉƒμ€„μ˜ κ°œμˆ˜λŠ” 100 μ΄ν•˜μ˜ μžμ—°μˆ˜μ΄λ‹€. λ‘˜μ§Έ 쀄뢀터 ν•œ 쀄에 ν•˜λ‚˜μ”© 전깃쀄이 Aμ „λ΄‡λŒ€μ™€ μ—°κ²°λ˜λŠ” μœ„μΉ˜μ˜ λ²ˆν˜Έμ™€ Bμ „λ΄‡λŒ€μ™€ μ—°κ²°λ˜λŠ”

www.acmicpc.net

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	int N;
	cin >> N;

	vector<pair<int, int>> poles;
	int dp[100];
	for (int i = 0; i < N; i++) {
		int a, b;
		cin >> a >> b;
		poles.push_back({ a, b });
		dp[i] = 1;
	}

	// a μ „λ΄‡λŒ€μ˜ 전깃쀄 μœ„μΉ˜λ₯Ό κΈ°μ€€μœΌλ‘œ μ •λ ¬
	sort(poles.begin(), poles.end());

	// a μ „λ΄‡λŒ€λ₯Ό κΈ°μ€€μœΌλ‘œ 전깃쀄을 μ •λ ¬ν–ˆμ„ λ•Œ
	// b μ „λ΄‡λŒ€λ„ 전깃쀄 μˆœμ„œκ°€ μ •λ ¬λ˜μ–΄μžˆμ–΄μ•Ό λ‘˜μ΄ μ—‰ν‚€μ§€ μ•ŠλŠ”λ‹€.
	for (int i = 0; i < N; i++)
		for (int j = 0; j < i; j++)
			if (poles[i].second > poles[j].second)
				dp[i] = max(dp[i], dp[j] + 1);

	// b μ „λ΄‡λŒ€μ˜ λΆ€λΆ„μ¦κ°€μˆ˜μ—΄μ€ λͺ¨λ‘ μ •λ ¬λœ μƒνƒœμ΄λ―€λ‘œ
	// μ›λž˜ κΈΈμ΄μ—μ„œ λΆ€λΆ„μ¦κ°€μˆ˜μ—΄μ˜ 길이λ₯Ό λΊ€λ‹€.
	cout << N - *max_element(dp, dp + N);
}

 

문제 : LCS(졜μž₯ 곡톡 λΆ€λΆ„ μˆ˜μ—΄)

https://www.acmicpc.net/problem/9251

 

9251번: LCS

LCS(Longest Common Subsequence, 졜μž₯ 곡톡 λΆ€λΆ„ μˆ˜μ—΄)λ¬Έμ œλŠ” 두 μˆ˜μ—΄μ΄ μ£Όμ–΄μ‘Œμ„ λ•Œ, λͺ¨λ‘μ˜ λΆ€λΆ„ μˆ˜μ—΄μ΄ λ˜λŠ” μˆ˜μ—΄ 쀑 κ°€μž₯ κΈ΄ 것을 μ°ΎλŠ” λ¬Έμ œμ΄λ‹€. 예λ₯Ό λ“€μ–΄, ACAYKP와 CAPCAK의 LCSλŠ” ACAKκ°€ λœλ‹€.

www.acmicpc.net

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int dp[1001][1001];

int main()
{
	string s1, s2;
	cin >> s1 >> s2;

	for (int i = 1; i <= s1.length(); i++)
		for (int j = 1; j <= s2.length(); j++)
			dp[i][j] = (s1[i - 1] == s2[j - 1]) ? dp[i - 1][j - 1] + 1 : max(dp[i][j - 1], dp[i - 1][j]);
	cout << dp[s1.length()][s2.length()];
}

 

문제 : λƒ…색

μ£Όμ–΄μ§„ μš©λŸ‰μ„ μ΄ˆκ³Όν•˜μ§€ μ•ŠμœΌλ©΄μ„œ 전체 이득이 μ΅œλŒ€κ°€ 될 수 μžˆλ„λ‘ ν•˜λŠ” λ¬Έμ œμ΄λ‹€.

 

https://www.acmicpc.net/problem/12865

 

12865번: ν‰λ²”ν•œ λ°°λ‚­

첫 쀄에 λ¬Όν’ˆμ˜ 수 N(1 ≤ N ≤ 100)κ³Ό μ€€μ„œκ°€ 버틸 수 μžˆλŠ” 무게 K(1 ≤ K ≤ 100,000)κ°€ μ£Όμ–΄μ§„λ‹€. 두 번째 쀄뢀터 N개의 쀄에 거쳐 각 물건의 무게 W(1 ≤ W ≤ 100,000)와 ν•΄λ‹Ή 물건의 κ°€μΉ˜ V(0 ≤ V ≤ 1,000)

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[100001];

int main()
{
	int n, k;
	cin >> n >> k;

	while (n--) {
		int w, v;
		cin >> w >> v;
		for (int i = 0; i <= k - w; i++)
			dp[i] = max(dp[i], dp[i + w] + v);
	}

	cout << *max_element(dp, dp + k);
}

 

https://www.acmicpc.net/problem/2293

 

2293번: 동전 1

첫째 쀄에 n, kκ°€ μ£Όμ–΄μ§„λ‹€. (1 ≤ n ≤ 100, 1 ≤ k ≤ 10,000) λ‹€μŒ n개의 μ€„μ—λŠ” 각각의 λ™μ „μ˜ κ°€μΉ˜κ°€ μ£Όμ–΄μ§„λ‹€. λ™μ „μ˜ κ°€μΉ˜λŠ” 100,000보닀 μž‘κ±°λ‚˜ 같은 μžμ—°μˆ˜μ΄λ‹€.

www.acmicpc.net

#include <iostream>
using namespace std;

int main()
{
	int n, k;
	cin >> n >> k;

	int dp[10001]{ 1 };
	for (int i = 0; i < n; i++) {
		int tmp;
		cin >> tmp;
		for (int j = tmp; j <= k; j++)
			dp[j] += dp[j - tmp];
	}

	cout << dp[k];
}

 

https://www.acmicpc.net/problem/11052

 

11052번: μΉ΄λ“œ κ΅¬λ§€ν•˜κΈ°

첫째 쀄에 λ―Όκ·œκ°€ κ΅¬λ§€ν•˜λ €κ³  ν•˜λŠ” μΉ΄λ“œμ˜ 개수 N이 μ£Όμ–΄μ§„λ‹€. (1 ≤ N ≤ 1,000) λ‘˜μ§Έ μ€„μ—λŠ” Piκ°€ P1λΆ€ν„° PNκΉŒμ§€ μˆœμ„œλŒ€λ‘œ μ£Όμ–΄μ§„λ‹€. (1 ≤ Pi ≤ 10,000)

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int N;
	cin >> N;

	int card[1001], dp[1001]{};
	for (int i = 1; i <= N; ++i)
		cin >> card[i];

	for (int i = 1; i <= N; i++)
		for (int j = 1; j <= i; j++)
			dp[i] = max(dp[i], dp[i - j] + card[j]);
	cout << dp[N];
}

 

문제 : μ΅œμ†ŒλΉ„μš© κ΅¬ν•˜κΈ°

https://www.acmicpc.net/problem/11066

 

11066번: 파일 ν•©μΉ˜κΈ°

문제 μ†Œμ„€κ°€μΈ κΉ€λŒ€μ „μ€ μ†Œμ„€μ„ μ—¬λŸ¬ μž₯(chapter)으둜 λ‚˜λˆ„μ–΄ μ“°λŠ”λ°, 각 μž₯은 각각 λ‹€λ₯Έ νŒŒμΌμ— μ €μž₯ν•˜κ³€ ν•œλ‹€. μ†Œμ„€μ˜ λͺ¨λ“  μž₯을 μ“°κ³  λ‚˜μ„œλŠ” 각 μž₯이 μ“°μ—¬μ§„ νŒŒμΌμ„ ν•©μ³μ„œ μ΅œμ’…μ μœΌλ‘œ μ†Œμ„€μ˜ οΏ½οΏ½

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[501][501];
int sum[501];

int main()
{
	int t;
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		for (int i = 1; i <= n; ++i) {
			cin >> sum[i];
			sum[i] += sum[i - 1];
		}

		for (int i = 1; i <= n; ++i)
			for (int start = 1; start + i <= n; ++start) {
				int end = start + i;
				dp[start][end] = 1e9;
				for (int j = start; j < end; ++j)
					dp[start][end] = min(dp[start][end], dp[start][j] + dp[j + 1][end] + sum[end] - sum[start - 1]);
			}
		cout << dp[1][n] << endl;
	}
}

 

https://www.acmicpc.net/problem/11049

 

11049번: ν–‰λ ¬ κ³±μ…ˆ μˆœμ„œ

첫째 쀄에 μž…λ ₯으둜 μ£Όμ–΄μ§„ 행렬을 κ³±ν•˜λŠ”λ° ν•„μš”ν•œ κ³±μ…ˆ μ—°μ‚°μ˜ μ΅œμ†Ÿκ°’μ„ 좜λ ₯ν•œλ‹€. 정닡은 231-1 보닀 μž‘κ±°λ‚˜ 같은 μžμ—°μˆ˜μ΄λ‹€. λ˜ν•œ, μ΅œμ•…μ˜ μˆœμ„œλ‘œ 연산해도 μ—°μ‚° νšŸμˆ˜κ°€ 231-1보닀 μž‘κ±°λ‚˜ κ°™οΏ½

www.acmicpc.net

#include <iostream>
#include <algorithm>
using namespace std;

int dp[501][501];
int a[501][2];

int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i][0] >> a[i][1];
		if (i > 1)
			dp[i - 1][i] = a[i - 1][0] * a[i - 1][1] * a[i][1];
	}

	for (int i = 2; i <= n; i++)	// 행렬이 3개 이상일 경우
		for (int start = 1; start + i <= n; start++) {
			int end = start + i;
			dp[start][end] = 1e9;
			for (int j = start; j < end; j++)
				dp[start][end] = min(dp[start][end], dp[start][j] + dp[j + 1][end] + a[start][0] * a[j][1] * a[end][1]);
		}
	cout << dp[1][n];
}

 

https://leetcode.com/problems/dungeon-game/

#include <vector>
#include <math.h>
using namespace std;

class Solution
{
public:
    int dp[201][201]{};

    int calculateMinimumHP(vector<vector<int>>& dungeon)
    {
        int m = dungeon.size();
        int n = dungeon[0].size();

        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                if (i == m - 1 && j == n - 1)
                    dp[i][j] = max(1, 1 - dungeon[i][j]);
                else if (i == m - 1)
                    dp[i][j] = max(1, dp[i][j + 1] - dungeon[i][j]);
                else if (j == n - 1)
                    dp[i][j] = max(1, dp[i + 1][j] - dungeon[i][j]);
                else
                    dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
            }
        }

        return dp[0][0];
    }
};

 

문제 : DFS+DP

https://www.acmicpc.net/problem/1520

 

1520번: 내리막 κΈΈ

여행을 λ– λ‚œ μ„Έμ€€μ΄λŠ” 지도λ₯Ό ν•˜λ‚˜ κ΅¬ν•˜μ˜€λ‹€. 이 μ§€λ„λŠ” μ•„λž˜ κ·Έλ¦Όκ³Ό 같이 μ§μ‚¬κ°ν˜• λͺ¨μ–‘이며 μ—¬λŸ¬ 칸으둜 λ‚˜λ‰˜μ–΄μ Έ μžˆλ‹€. ν•œ 칸은 ν•œ 지점을 λ‚˜νƒ€λ‚΄λŠ”λ° 각 μΉΈμ—λŠ” κ·Έ μ§€μ μ˜ 높이가 μ“°μ—¬ 있으�

www.acmicpc.net

#include <iostream>
using namespace std;

int M, N;
int h[500][500], dp[500][500];
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };

int f(int y, int x, int hei)
{
	if (x < 0 || x >= N || y < 0 || y >= M || h[y][x] >= hei)
		return 0;
	else if (y == M - 1 && x == N - 1)
		return 1;
	else if (dp[y][x] >= 0)
		return dp[y][x];

	dp[y][x] = 0;
	for (int i = 0; i < 4; i++)
		dp[y][x] += f(y + dir[i][0], x + dir[i][1], h[y][x]);
	return dp[y][x];
}

int main()
{
	cin >> M >> N;
	for (int i = 0; i < M; i++)
		for (int j = 0; j < N; j++) {
			cin >> h[i][j];
			dp[i][j] = -1;
		}
	cout << f(0, 0, h[0][0] + 1);
}

 

문제 : DFS+BFS+DP

https://leetcode.com/problems/word-ladder-ii/

 

Word Ladder II - LeetCode

Can you solve this real interview question? Word Ladder II - A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: * Every adjacent pair of words diffe

leetcode.com

#include <vector>
#include <map>
#include <queue>
#include <string>
using namespace std;

class Solution {
public:
    vector<vector<string>> answers;
    vector<string> answer;
    bool check[500];
    map<string, int> counts;
    int minCount;

    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        minCount = 0;
        queue<pair<string, int>> q;
        q.push({ beginWord, 0 });
        while (!q.empty()) {
            string word = q.front().first;
            int cnt = q.front().second;
            q.pop();

            if (word == endWord) {
                minCount = cnt;
                break;
            }

            for (int i = 0; i < wordList.size(); i++)
            {
                if (check[i] || isNearWord(word, wordList[i]) == false)
                    continue;
                check[i] = true;
                q.push({ wordList[i], cnt + 1 });
            }
        }

        memset(check, false, sizeof(check));
        answer.push_back(beginWord);
        dfs(beginWord, endWord, wordList, 0);
        return answers;
    }

    bool dfs(string& curWord, string& endWord, vector<string>& wordList, int count) {
        if (count == minCount) {
            if (curWord != endWord)
                return false;
            else {
                answers.push_back(answer);
                return true;
            }
        }
        else if (counts.find(curWord) != counts.end() && counts[curWord] <= count)
            return false;

        bool movable = false;
        for (int i = 0; i < wordList.size(); i++) {
            if (check[i] || isNearWord(curWord, wordList[i]) == false)
                continue;

            check[i] = true;
            answer.push_back(wordList[i]);
            if (dfs(wordList[i], endWord, wordList, count + 1))
                movable = true;
            answer.pop_back();
            check[i] = false;
        }

        if (movable == false)
            counts[curWord] = count;
        return movable;
    }

    bool isNearWord(string& cur, string& next) {
        int cnt = 0;
        for (int i = 0; i < cur.size(); i++)
            if (cur[i] != next[i])
                cnt++;
        return cnt == 1;
    }
};

 

문제 : left to right

https://leetcode.com/problems/candy/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

#include <vector>
using namespace std;

class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size();
        vector<int> candyCount(n, 1);

        // left to right
        for (int i = 1; i < n; ++i) {
            if (ratings[i - 1] < ratings[i]) {
                candyCount[i] = candyCount[i - 1] + 1;
            }
        }

        // right to left
        for (int i = n - 2; i >= 0; --i) {
            if (ratings[i] > ratings[i + 1]) {
                candyCount[i] = max(candyCount[i], candyCount[i + 1] + 1);
            }
        }

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

 

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

#include <vector>
#include <math.h>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size = prices.size();
        vector<int> leftProfit(size, 0);
        vector<int> rightProfit(size, 0);

        int minPrice = prices[0];
        for (int i = 1; i < size; ++i) {
            minPrice = min(prices[i], minPrice);
            leftProfit[i] = max(leftProfit[i - 1], prices[i] - minPrice);
        }

        int maxPrice = prices[size - 1];
        for (int i = size - 2; i >= 0; --i) {
            maxPrice = max(prices[i], maxPrice);
            rightProfit[i] = max(rightProfit[i + 1], maxPrice - prices[i]);
        }

        int answer = 0;
        for (int i = 0; i < size; ++i)
            answer = max(answer, leftProfit[i] + rightProfit[i]);
        return answer;
    }
};
μ €μž‘μžν‘œμ‹œ (μƒˆμ°½μ—΄λ¦Ό)
'πŸ“ Computer Science/✏ Algorithm' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€
  • [C++] μ΅œλ‹¨ 경둜(λ‹€μ΅μŠ€νŠΈλΌ, ν”Œλ‘œμ΄λ“œ 와샬, 벨만 ν¬λ“œ)
  • [C++] 깊이 μš°μ„  탐색(DFS), λ„ˆλΉ„ μš°μ„  탐색(BFS)
  • [C++] 덱(Deque)
  • [C++] 큐(Queue), μš°μ„ μˆœμœ„ 큐(Priority Queue)
Blxxming
Blxxming
CS 지식과 κ³΅λΆ€ν•˜λ‹€ 배운 것, κ²½ν—˜ν•œ 것 등을 κΈ°λ‘ν•˜λŠ” λΈ”λ‘œκ·Έμž…λ‹ˆλ‹€.
  • Blxxming
    πŸ’‘λ²ˆλœ©πŸ’‘
    Blxxming
  • 전체
    였늘
    μ–΄μ œ
  • 곡지사항

    • Tech Interview
    • πŸ“š Tech (246)
      • πŸ“ Computer Science (96)
        • ✏ OS (12)
        • ✏ Network & Web (10)
        • ✏ Database (11)
        • ✏ Data Structure (6)
        • ✏ Algorithm (40)
        • ✏ Design Pattern (9)
        • ✏ Cloud Computing (3)
        • ✏ (5)
      • πŸ“ Language (73)
        • ✏ Language (6)
        • ✏ C & C++ (11)
        • ✏ C# (19)
        • ✏ JAVA (37)
      • πŸ“ Game (43)
        • ✏ Computer Graphics (2)
        • ✏ Unity (14)
        • ✏ Unreal (26)
        • ✏ (1)
      • πŸ“ Book (34)
        • ✏ Effective (3)
        • ✏ Game Server (16)
        • ✏ Clean Code (14)
        • ✏ (1)
  • hELLOΒ· Designed Byμ •μƒμš°.v4.10.0
Blxxming
[C++] 동적 κ³„νšλ²•(Dynamic Programming)
μƒλ‹¨μœΌλ‘œ

ν‹°μŠ€ν† λ¦¬νˆ΄λ°”