๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ Computer Science/Algorithm

[Algorithm] ์กฐํ•ฉ(Combination)์ด๋ž€? (feat.Swift)

by Fomagran ๐Ÿ’ป 2021. 6. 27.
728x90
๋ฐ˜์‘ํ˜•

 

์•ˆ๋…•ํ•˜์„ธ์š” Foma ๐Ÿ‘Ÿ ์ž…๋‹ˆ๋‹ค!

 

์˜ค๋Š˜์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ์—์„œ ์ •๋ง ๋นˆ๋ฒˆํ•˜๊ฒŒ ์‚ฌ์šฉ๋˜๋Š” "์กฐํ•ฉ" ์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


์กฐํ•ฉ์ด๋ž€?

 

n๊ฐœ์˜ ์›์†Œ์—์„œ r ๊ฐœ์˜ ์›์†Œ๋ฅผ  ์ˆœ์„œ์— ์ƒ๊ด€์—†์ด ๋ฝ‘๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ - ๋‚˜๋ฌด  ์œ„ํ‚ค -

 

์ˆœ์—ด๊ณผ ๋‹ค๋ฅด๊ฒŒ ์ˆœ์„œ๋Š” ์ค‘์š”ํ•˜์ง€ ์•Š์•„์š”.

 

์‰ฝ๊ฒŒ ์„ค๋ช…ํ•˜๋ฉด ๋ฌผ๊ฑด์„ ์‚ฌ๊ณ  ์ด ๊ฐ€๊ฒฉ์„ ๊ตฌํ•˜๋Š” ๊ฒƒ๊ณผ ๋น„์Šทํ•ด์š”.

 

๊ณผ์ผ๋กœ ์˜ˆ๋ฅผ ๋“ค๋ฉด ์‚ฌ๊ณผ,ํฌ๋„,์ˆ˜๋ฐ•์ด ์žˆ๋‹ค๋ฉด

 

์‚ฌ๊ณผ,ํฌ๋„,์ˆ˜๋ฐ•

 

ํฌ๋„,์‚ฌ๊ณผ,์ˆ˜๋ฐ•

 

์ˆ˜๋ฐ•,์‚ฌ๊ณผ,ํฌ๋„

 

... ๋“ฑ ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ์‚ฌ๋„ ์ด ๊ฐ€๊ฒฉ์„ ๋˜‘๊ฐ™๊ฒ ์ฃ ?

 

์ฆ‰, ์ด๋ฃจ์–ด์ง„ ๊ณผ์ผ์ด ๋˜‘๊ฐ™๋‹ค๋ฉด ํ•˜๋‚˜์˜ ์กฐํ•ฉ์œผ๋กœ ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.


์ฝ”๋“œ ๊ตฌํ˜„

 

๋จผ์ € ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ด์„ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

var cases:[[Int]] = []

 

combination์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์„ค์ •ํ•ด์ฃผ๋Š”๋ฐ

 

์ธ๋ฑ์Šค๋“ค์„ ๋‹ด๊ณ ์žˆ๋Š” indexes

 

๋ฝ‘์•„์•ผํ•  ๊ฐฏ์ˆ˜๋ฅผ ์ •ํ•  pickCount

 

ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ํ‘œ์‹œํ•  current

 

๋ฝ‘์€ ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•  picked

 

๋กœ ๋ฐ›์•„์ค๋‹ˆ๋‹ค.

 

func combination(indexes: [Int], pickCount: Int, current: Int, picked: [Int]) {...}

 

๋งŒ์•ฝ ํ˜„์žฌ ์ธ๋ฑ์Šค๊ฐ€ ๋ฝ‘์•„์•ผ ํ•  ์ธ๋ฑ์Šค๊นŒ์ง€ ์™”๋‹ค๋ฉด cases์— picked๋ฅผ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

 

   if current == pickCount {
        cases.append(picked)
        return
    }

 

 

indexes๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ฐฉ๋ฌธํ•œ ๊ณณ์„ true๋กœ ํ•ด์ฃผ๊ณ  ์ƒˆ๋กญ๊ฒŒ ๋ฝ‘์€ ์ˆซ์ž๋“ค์„ ๋„ฃ์–ด ์žฌ๊ท€ํ•ด์ค๋‹ˆ๋‹ค.

 

 indexes
        .enumerated()
        .forEach{
            if !initialVisited[$0.offset] {
                initialVisited[$0.offset] = true
                var newPicked = picked
                newPicked.append($0.element)
                combination(indexes: indexes, pickCount: pickCount, current: current+1, picked: newPicked,visited: initialVisited)
            }
        }

 

์•„๋ž˜์™€ ๊ฐ™์ด ์›ํ•˜๋Š” ์กฐ๊ฑด์œผ๋กœ ์‹คํ–‰์‹œํ‚ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ์กฐ๊ฑด์— ๋งž๊ฒŒ ์กฐํ•ฉ๋“ค์ด ์ถœ๋ ฅ๋˜๋Š”๊ฑธ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

combination(indexes: [1,2,3,4,5], pickCount: 3, current: 0, picked: [], visited: [])
print(cases)
  
//[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]

์ „์ฒด ์†Œ์Šค ์ฝ”๋“œ

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€