Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d07ea5a

Browse files
committed
feat: 分割子数组
1 parent dea70e1 commit d07ea5a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
let canPartition = function (nums) {
6+
let sum = nums.reduce((a, b) => a + b);
7+
8+
let target = sum / 2;
9+
if (Math.ceil(target) !== target) {
10+
return false;
11+
}
12+
13+
let n = nums.length;
14+
let dp = new Array(n);
15+
for (let i = 0; i < dp.length; i++) {
16+
dp[i] = new Array(target + 1).fill(false);
17+
}
18+
19+
for (let j = 0; j <= target; j++) {
20+
dp[0][j] = nums[0] === target ? true : false;
21+
}
22+
23+
for (let i = 0; i < dp.length; i++) {
24+
dp[i][0] = true;
25+
}
26+
27+
for (let i = 1; i < dp.length; i++) {
28+
for (let j = 0; j <= target; j++) {
29+
let num = nums[i];
30+
31+
let pick = dp[i - 1][j - num] || false;
32+
let notPick = dp[i - 1][j] || false;
33+
34+
let result = pick || notPick;
35+
dp[i][j] = result;
36+
37+
if (j == target && result) {
38+
return true;
39+
}
40+
}
41+
}
42+
43+
return dp[n - 1][target];
44+
};
45+
46+
console.log(canPartition([1, 2, 3, 5]));
47+
48+
/**
49+
* 这个问题的思路在于,先把数组之和除以二,记为target。只要任意组合的子数组能凑成target,也就说明剩下的一定也能凑成target。
50+
* 1. 除以二后有小数点的直接失败,因为一定不可能是两个整数子数组相凑的结果。
51+
* 2. 只要用任意数量的子数组可以拼凑出来target的值,也就是dp数组的任意一层的最右边的值计算出是true,那么整题的结果就为true。因为不论你用几个值凑出了target值,哪怕只用了一个值。另外剩下的值之和一定也是target。
52+
*/

0 commit comments

Comments
 (0)