How to get all subarrays from an array by using JavaScript All In One
How to get all subarrays from an array by using JavaScript All In One
JavaScript 动态生成其所有的
子数组
算法
difficulty: Medium
/ 难度: 中等
errorrs
two pointers
function getAllSubArrays(arr, start, end, result) {
if (end === arr.length) {
return result;
} else if (start > end) {
// Increment the end point and start from 0
getAllSubArrays(arr, 0, end + 1, result);
} else {
// Print the subarray and increment the starting point
let temp = [];
for(let i = start; i < end; i++) {
temp.push(arr[i]);
}
// 丢失 子数组 bug ❌
// temp.push(arr[end]);
let str = temp.join(',');
// let str = temp.join('');
// 去重 bug ❌ & 去空
if(!result.includes(str) && temp.length) {
result.push(str);
}
console.log(`subArray =`, temp);
getAllSubArrays(arr, start + 1, end, result);
}
return result;
}
// test
// getAllSubArrays([1,1,2,1,1], 0, 0, [])
// ['1', '1,1', '1,1,2', '1,2', '2', '1,1,2,1', '1,2,1', '2,1']
getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => str.split(`,`));
// getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => [...str]);
function getAllSubArrays(arr, start, end, result) {
if (end === arr.length) {
return result;
} else if (start > end) {
// Increment the end point and start from 0
getAllSubArrays(arr, 0, end + 1, result);
} else {
let temp = [];
for(let i = start; i < end; i++) {
temp.push(arr[i]);
}
// ✅ 丢失 子数组 bug fixed
temp.push(arr[end]);
let str = temp.join(',');
// let str = temp.join('');
// 去重 bug ❌ & 去空
if(!result.includes(str) && temp.length) {
result.push(str);
}
console.log(`subArray =`, temp);
getAllSubArrays(arr, start + 1, end, result);
}
return result;
}
// test
// getAllSubArrays([1,1,2,1,1], 0, 0, [])
// ['1', '1,1', '1,1,2', '1,2', '2', '1,1,2,1', '1,2,1', '2,1', '1,1,2,1,1', '1,2,1,1', '2,1,1']
// getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => str.split(`,`));
getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => str.split(`,`)).map(arr => arr.map(Number));
// getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => [...str]);
// getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => [...str]).map(arr => arr.map(Number));
bugs
function numberOfSubarrays(nums: number[], k: number): number {
let count = 0;
// sub-arrays
// const subarrays = getAllSubarrays(nums);
const subarrays = getAllSubArrays(nums, 0, 0, []);
// const subarrays = getAllSubArrays(nums, 0, 0, []).map(str => str.split(`,`));
// const subarrays = getAllSubArrays([1,1,2,1,1], 0, 0, []).map(str => str.split(`,`)).map(arr => arr.map(Number))
console.log(`subarrays =`, subarrays)
for(let subarray of subarrays) {
// error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
// 算术运算的左侧必须是“any”、“number”、“bigint”或枚举类型。
// let odds = subarray.filter(i => i % 2 !== 0);
// let odds = subarray.map(Number).filter(i => i % 2 !== 0);
// 不去重 子数组变多, 导致重复计数 bug ❌ 💩
let odds = subarray.filter(i => i % 2 !== 0);
if(odds.length === k) {
count++;
}
}
return count;
};
// 双指针 ✅
// function getAllSubArrays(arr:number[] = [], start:number = 0, end:number = 0, result:string[] = []) {
function getAllSubArrays(arr:number[] = [], start:number = 0, end:number = 0, result:number[][] = []) {
if (end === arr.length) {
return result;
} else if (start > end) {
// Increment the end point and start from 0
getAllSubArrays(arr, 0, end + 1, result);
} else {
// Print the subarray and increment the starting point
let temp:number[] = [];
for(let i = start; i < end; i++) {
temp.push(arr[i]);
}
// let str = temp.join(',');
// // let str = temp.join('');
// // 去重 丢失 子数组 bug ❌ & 去空
// if(!result.includes(str) && temp.length) {
// result.push(str);
// // console.log(`subArray =`, temp);
// }
// 去空 ✅
if(temp.length) {
result.push(temp);
// console.log(`subArray =`, temp);
}
getAllSubArrays(arr, start + 1, end, result);
}
return result;
}
// function getAllSubarrays(arr: number[], left: number, right: number): number[][] {
// let result: number[][] = [];
// while(left <= arr.length - 1) {
// result.push(arr.slice(left, right));
// left++;
// }
// left = 0;
// right = arr.length - 1;
// while(right >= 0) {
// result.push(arr.slice(left, right));
// right--;
// }
// console.log(`result =`, result);
// return result;
// };
// 滑动 ❌
// function getAllSubarrays(arr: number[]): number[][] {
// let result: number[][] = [];
// let len = arr.length;
// while(len) {
// let temp = [];
// let step = arr.length - len + 1;
// console.log(`❓ step =`, step)
// for(let i = 0; i <= arr.length; i++) {
// if(arr[step]) {
// temp.push(arr.slice(i, step));
// result.push(temp);
// }
// step++;
// }
// console.log(`❌ result =`, result);
// len--;
// }
// console.log(`result =`, result);
// return result;
// };
// 递归: 排列组合 permutation & composition
// function getAllPermutation(arr: number[]): number[][] {
// let result: number[][] = [];
// for(let i = 0; i < arr.length; i++) {
// let temp = arr[i];
// let others = getAllPermutation([...arr.slice(0, i), ...arr.slice(i)]);
// for(let other of others) {
// result.push([temp, ...other]);
// }
// }
// return result;
// };
solutions
function numberOfSubarrays(nums: number[], k: number): number {
let len = nums.length;
let arr = new Array(len + 1).fill(0);
arr[0] = 1;
let count = 0;
let temp = 0;
for (let num of nums) {
temp += num & 1;
if (temp - k >= 0) {
count += arr[temp - k];
}
arr[temp]++;
}
return count;
};
two pointers
function getAllSubArrays(arr, start, end, result) {
if (end === arr.length) {
return result;
} else if (start > end) {
// Increment the end point and start from 0
getAllSubArrays(arr, 0, end + 1, result);
} else {
let temp = [];
for(let i = start; i < end; i++) {
temp.push(arr[i]);
}
// ✅ 丢失 子数组 bug fixed
temp.push(arr[end]);
// ✅ 去重 bug fixed, 没有必要去空
// if(temp.length) {
// result.push(str);
// }
result.push(temp);
console.log(`subArray =`, temp);
getAllSubArrays(arr, start + 1, end, result);
}
return result;
}
// test ✅
getAllSubArrays([1,1,2,1,1], 0, 0, [])
// [[1],[1,1],[1],[1,1,2],[1,2],[2],[1,1,2,1],[1,2,1],[2,1],[1],[1,1,2,1,1],[1,2,1,1],[2,1,1],[1,1],[1]]
still bug ❓
function numberOfSubarrays(nums: number[], k: number): number {
let count = 0;
// sub-arrays
const subarrays = getAllSubArrays(nums, 0, 0, []);
const all_subarrays = getAllSubArrays(nums, 0, 0, []).map(arr => arr.join(`,`));
console.log(`subarrays =`, all_subarrays)
for(let subarray of subarrays) {
let odds = subarray.filter(i => i % 2 !== 0);
if(odds.length === k) {
count++;
}
}
return count;
};
// 双指针 ✅
function getAllSubArrays(arr:number[] = [], start:number = 0, end:number = 0, result:number[][] = []) {
if (end === arr.length) {
return result;
} else if (start > end) {
// Increment the end point and start from 0
getAllSubArrays(arr, 0, end + 1, result);
} else {
// Print the subarray and increment the starting point
let temp:number[] = [];
for(let i = start; i < end; i++) {
temp.push(arr[i]);
}
// bug fixed ✅
temp.push(arr[end]);
// 不需要去重,去空 ✅
result.push(temp);
// console.log(`subArray =`, temp);
getAllSubArrays(arr, start + 1, end, result);
}
return result;
}
/*
Time Limit Exceeded
14 / 38 testcases passed
*/
demos
// 双指针 ???
// function numberOfSubarrays(nums: number[], k: number): number {
// let count = 0;
// // sub-arrays
// const subarrays = getAllSubarrays(nums);
// for(let subarray of subarrays) {
// let odds = subarray.filter(i => i % 2 !== 0);
// if(odds.length === k) {
// count++;
// }
// }
// return count;
// };
// 滑动 ❌
// function getAllSubarrays(arr: number[]): number[][] {
// let result: number[][] = [];
// let len = arr.length;
// while(len) {
// let temp = [];
// let step = arr.length - len + 1;
// console.log(`❓ step =`, step)
// for(let i = 0; i <= arr.length; i++) {
// if(arr[step]) {
// temp.push(arr.slice(i, step));
// result.push(temp);
// }
// step++;
// }
// console.log(`❌ result =`, result);
// len--;
// }
// console.log(`result =`, result);
// return result;
// };
// 递归: 排列组合 permutation & composition
// function getAllPermutation(arr: number[]): number[][] {
// let result: number[][] = [];
// for(let i = 0; i < arr.length; i++) {
// let temp = arr[i];
// let others = getAllPermutation([...arr.slice(0, i), ...arr.slice(i)]);
// for(let other of others) {
// result.push([temp, ...other]);
// }
// }
// return result;
// };
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
test
// export {};
function printSubArrays(arr, start = 0, end = 0) {
// Stop if we have reached the end of the array
if (end === arr.length) {
return;
} else if (start > end) {
// Increment the end point and start from 0
printSubArrays(arr, 0, end + 1);
} else {
// Print the subarray and increment the starting point
let str = `[`;
for(var i = start; i < end; i++) {
str += arr[i] + `,`;
}
str += arr[end] + `]`;
console.log(`subArray =`, str);
printSubArrays(arr, start + 1, end);
}
return;
}
// test
let arr = [ 1, 2, 3, 4];
printSubArrays(arr, 0, 0);
// subArray = [1]
// subArray = [1,2]
// subArray = [2]
// subArray = [1,2,3]
// subArray = [2,3]
// subArray = [3]
// subArray = [1,2,3,4]
// subArray = [2,3,4]
// subArray = [3,4]
// subArray = [4]
subarray vs subsequence vs subset
子数组
子序列
子集合
https://www.geeksforgeeks.org/array-subarray-subsequence-and-subset/
MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray
refs
https://www.geeksforgeeks.org/generating-subarrays-using-recursion/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18262992
未经授权禁止转载,违者必究!