From 89584dfde521275679dd28cdfc6a1bc3f0447dc9 Mon Sep 17 00:00:00 2001 From: aadil42 <77232799+aadil42@users.noreply.github.com> Date: Thu, 2 Jan 2025 15:30:13 +0530 Subject: [PATCH] Create 0698-partition-to-k-equal-sum-subsets.js Solved partition-to-k-equal-sum-subsets --- .../0698-partition-to-k-equal-sum-subsets.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 javascript/0698-partition-to-k-equal-sum-subsets.js diff --git a/javascript/0698-partition-to-k-equal-sum-subsets.js b/javascript/0698-partition-to-k-equal-sum-subsets.js new file mode 100644 index 000000000..6263ea59f --- /dev/null +++ b/javascript/0698-partition-to-k-equal-sum-subsets.js @@ -0,0 +1,32 @@ +/** + * Backtracking. + * Time O(n^n) | Space O(n) + * https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var canPartitionKSubsets = function(nums, k) { + + const target = nums.reduce((acc, num) => acc+num, 0)/k; + nums.sort((a,b)=> b-a); + const taken = new Set(); + + const dfs = (index, k, currSum) => { + if (k === 0) return true; + if (currSum === target) return dfs(0, k-1, 0); + + for (let i = index; i < nums.length; i++) { + if (currSum+nums[i] > target) continue; + if (taken.has(i)) continue; + if (i > 0 && !taken.has(i-1) && nums[i] === nums[i-1]) continue; + + taken.add(i); + if (dfs(i+1, k, currSum+nums[i])) return true; + taken.delete(i); + } + return false; + } + + return dfs(0,k,0); +};