-
Notifications
You must be signed in to change notification settings - Fork 18
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
[js] 实现0和1的排列组合 #23
Comments
var res=[]
for(var i=0;i<size*size;i++){
var item=i.toString(2).split("").map(function(item){return parseInt(item)})
while(item.length<size){item.unshift(0)}
res.push(item)
} |
|
这个题很不错。👍 (() => {
let feed = [0, 1]
function getArr (size, index = 1, result = feed) {
return size === index ? result : getArr(size, index + 1, [].concat(...feed.map(item =>
new Array(feed.length ** index).fill(item).map((item, itemLen) =>
[].concat(result[itemLen], item))
)
))
}
let arr = getArr(4)
console.log(JSON.stringify(arr))
})() 以及一个抛弃灵活性的实现 (() => {
function getArr(size) {
return new Array(size ** 2).fill().map((_, i) => i.toString(2).padStart(size, 0))
}
let arr = getArr(4)
console.log(JSON.stringify(arr))
})() |
function getArr(size: number) {
const result: number[][] = [];
(function loop(arr: number[] = []) {
if (arr.length < size) {
loop([...arr, 0]);
loop([...arr, 1]);
} else {
result.push(arr);
}
})();
return result;
} |
根据 @zouchengzhuo 的解答,做了一点小修改,先计算出n位二进制数最大对应的十进制数,再将十进制转成二进制(toString(2)就能实现,位数不够的高位补0),即可得到所有0,1组合。
|
根据@Jiasm 答案修改 (() => {
function getArr(size) {
return new Array(size ** 2).fill().map((_, i) => i.toString(2).padStart(size, 0).split('').map(i => +i))
}
let arr = getArr(5)
console.log(JSON.stringify(arr))
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
要求:给定一个组合长度,输出由
0
和1
在该长度内排列组合形成的二维数组。例如:
其实这个实现很简单的,不用想太复杂了:smile:
The text was updated successfully, but these errors were encountered: