폰켓몬

김현민·2021년 9월 13일
0

Algorithm

목록 보기
75/126
post-thumbnail

내 코드


// 조합구하는 함수
function combination(arr, selectNum) {
  const result = []
  if (selectNum === 1) return arr.map((v) => [v])
  arr.forEach((v, idx, arr) => {
    const fixed = v
    const restArr = arr.slice(idx + 1)
    const combinationArr = combination(restArr, selectNum - 1)
    const combineFix = combinationArr.map((v) => [fixed, ...v])
    result.push(...combineFix)
  })
  return result
}


function solution(nums) {
  var answer = -1000

  var selec = nums.length / 2

  var tt = selec + nums.length - 1

  var temp = combination(nums, selec)
  
  
  const res = []
  
  //  조합에서 중복을 제거하는 반복문
  for (let i = 0; i < temp.length; i++) {
    const setTt = new Set(temp[i])
    const tt = [...setTt]
    const max = tt.length
    if (max > answer) answer = max
  }

  return answer
}

이렇게 했더니 런타임오류가 발생한다..


다른사람의 코드

function solution(nums) {
  var answer = -1000

  const tt = new Set()

  for (const number of nums) {
    tt.add(number)
  }

  if (tt.size < nums.length / 2) {
    answer = tt.size
  } else {
    answer = nums.length / 2
  }

  return answer
}

solution([3, 3, 3, 2, 2, 4])

Set으로 아예 변수를 지정해놓고 add 하면 중복이 제거되면서 추가되나보다..
중복이 제거된 size의 값으로 값을 구하면 된다

profile
Jr. FE Dev

0개의 댓글