Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 所有的可能组合数

所有的可能组合数

请设计一个 combinations 函数,它接收一个数字数组,要求返回这些数字的所有可能组合情况。

 function combinations(arr) {
	 let result = [[]]
	 for(let n of arr) {
		 let len = result.length;
		 for(let i = 0;i < len; i ++) {
			 result.push([...result[i],n])
		 }
	 }
	 return result
 }
 console.log(111,combinations([1,2,3]))

拓展

给定一个数,和一个数组,返回所有可能的组合情况,要求组合中数字之和等于给定的数。

方法一用上面的方法后,再进行便利求和,等于这个数的拿出来即可。

方法2

 function findCombinations(arr,target) {
	 let res = [];
	 function inner(start,path,sum) {
		 if(sum === target) {
			 res.push([...path])
			 return 
		 }
		 for(let i = start; i < arr.length; i ++) {
			 if(sum + arr[i] <=  target) {
				 path.push(arr[i])
				  inner(start,path,sum + arr[i])
				  path.pop()
			 }
		 }
	 }
	 inner(0,[],0)
	 return res
 }
 
 
 
 let arr = [2, 4, 6, 8];
 let target = 10;
 let combinations = findCombinations(arr, target);
 console.log(combinations);
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人