Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create 0698-partition-to-k-equal-sum-subsets.js #3784

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions javascript/0698-partition-to-k-equal-sum-subsets.js
Original file line number Diff line number Diff line change
@@ -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);
};