Computer Science/알고리즘

leetcode 416) Partition Equal Subset Sum

eeeun:) 2022. 1. 4. 21:55
반응형

LV. Medium 🧐

https://leetcode.com/problems/partition-equal-subset-sum/

 

Partition Equal Subset Sum - 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

 

문제

Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

 

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

 

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

 

문제 해결법

1. nums의 총합이 짝수여야 된다(2개의 조합으로 나누기 때문) -> 홀수면 false 리턴!

2. dp로 문제를 풀면 된다

 

(sum / 2) 가 하나의 조합에서 나와야되는 합계이다

sum이 20이라고 생각하고 1 ~ (sum / 2)인 bool 배열을 만들고 다 false로 채워보자

1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 0 0 0 0 0

nums[0] = 2 이면 1개로 만들 수 있는 합계의 조합은 2이다 -> 만들 수 있는 수를 true로 바꾸기

1 2 3 4 5 6 7 8 9 10
0 1 0 0 0 0 0 0 0 0

nums[1] = 1 이면 2개로 만들 수 있는 합계의 조합은 1, 2, 3이다

2는 이미 true로 되어있고, 1은 nums[1]의 값이니깐 true로 바꾸고,

그렇다면 3은 어떻게 나온것일까?

 

10부터 1까지 역순으로 돌면서 true인 값을 찾는다

이미 true인 값은 이전의 수로 만들 수 있는 조합의 합계이므로, true인 값 + 현재 nums의 값 = 만들 수 있는 조합의 합계가 된다

 

이런 식으로 nums배열을 다 돌려서 10이 true가 되었다면 nums의 조합으로 sum / 2의 값을 만들 수 있다는 것!!

 

해결 코드
class Solution {
private:
	int sum;

public:
	bool canPartition(vector<int>& nums) {
		sum = 0;
		for (int i = 0; i < nums.size(); ++i)
			sum += nums[i];
		if (sum % 2 == 1)
			return false;

		// 만들 수 있는 조합들의 합계 저장할 백터
		vector<bool>check(sum + 1, false);
		check[0] = true;
		for (int i = 0; i < nums.size(); ++i) {
			if (nums[i] > sum / 2)
				return false;
			for (int j = sum / 2; j >= nums[i]; --j) {
				check[j] = check[j] || check[j - nums[i]];
			}
		}
		return check[sum / 2];
	}
};

728x90