Scribbling

[C++] vector sum, dp table with vector 본문

Computer Science/C++

[C++] vector sum, dp table with vector

focalpoint 2023. 9. 2. 02:45

 

LeetCode: 416. Partition Equal Subset Sum

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

 

Partition Equal Subset Sum - LeetCode

Can you solve this real interview question? Partition Equal Subset Sum - Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.   Example 1: I

leetcode.com

class Solution{
	public:
		
		vector<int> nums;
		vector<vector<optional<bool>>> dp;
		
		bool canPartition(vector<int>& nums) {
			int total = accumulate(nums.begin(), nums.end(), 0);
			if (total % 2 == 1) return false;
			int n = nums.size();
			int goal = total/2;
			this->nums = nums;
			this->dp = vector<vector<optional<bool>>>(n+1, vector<optional<bool>>(goal+1, nullopt));
			return dfs(0, goal);
		}
		
		bool dfs(int idx, int goal) {
			if (goal < 0) {
				return false;
			}
			
			if (idx == nums.size()) {
				return goal == 0;
			}
			
            if (dp[idx][goal] != nullopt) return dp[idx][goal] == true;

			if (dfs(idx+1, goal-nums[idx]) == true) {
				dp[idx][goal] = true;
				return true;
			}
			
			if (dfs(idx+1, goal) == true) {
				dp[idx][goal] = true;
				return true;
			}
			
			dp[idx][goal] = false;
			return false;
			
		}
		
};