๊ด€๋ฆฌ ๋ฉ”๋‰ด

Coding Planet

level1. ์นด๋“œ ๋ญ‰์น˜ Java (์žฌ๊ท€ ํ•จ์ˆ˜ ํ’€์ด) ๋ณธ๋ฌธ

๐ŸŽ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

level1. ์นด๋“œ ๋ญ‰์น˜ Java (์žฌ๊ท€ ํ•จ์ˆ˜ ํ’€์ด)

jhj.sharon 2023. 8. 26. 17:59
๋ฐ˜์‘ํ˜•

โœจ ๋ฌธ์ œ

๐Ÿ’ป์ฝ”๋“œ

class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        return canForm(goal, cards1, cards2, 0, 0, 0)? "Yes" : "No";
    }
    
    private static boolean canForm(String[] goal, String[] cards1, String[] cards2, int idxGoal, int idx1, int idx2){
        if(idxGoal == goal.length){
            return true; //base case
        }
        
        if(idx1 < cards1.length && cards1[idx1].equals(goal[idxGoal])){
            if(canForm(goal, cards1, cards2, idxGoal +1, idx1 +1, idx2)){
                return true;
            }
        }
        if(idx2 < cards2.length && cards2[idx2].equals(goal[idxGoal])){
            if(canForm(goal, cards1, cards2, idxGoal +1, idx1, idx2+1)){
                return true;
            }
        }
            
        return false;
    }
}

 

๐Ÿ‘ฉ‍๐Ÿ’ป ํ’€์ด ๋ฐฉ๋ฒ•

  •  ์žฌ๊ท€ํ•จ์ˆ˜(https://sharonprogress.tistory.com/246)๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.
  • ๋ฌธ์ž์—ด ๋ฐฐ์—ด์ธ cards1, cards2, goal์„ ๋น„๊ตํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๊ฐ ๋ฌธ์ž์—ด ์š”์†Œ๋ฅผ ๊ฐ€๋ฅดํ‚ค๋Š” ์ธ๋ฑ์Šค๊ฐ€ ํ•„์š”ํ•˜๋‹ค. ์ด ์ธ๋ฑ์Šค์˜ ์˜ ๋ณ€ํ™”๋กœ ๊ฐ ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•  ์ˆ˜ ์žˆ๋‹ค.
  • canFormํ•จ์ˆ˜๋Š” ์ฃผ์–ด์ง„ ๋ชฉํ‘œ ๋ฐฐ์—ด goal๊ณผ ๋‘ ์นด๋“œ ๋ญ‰์น˜๋ฅผ ๋น„๊ตํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. idxGoal, idx1, idx2๋Š” ๊ฐ  goal, cards1, cards2 ๋ฐฐ์—ด์˜ ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.
  • ๋ฒ ์ด์Šค ์ผ€์ด์Šค: ๋งŒ์•ฝ idxGoal์ด goal ๋ฐฐ์—ด์˜ ๊ธธ์ด์™€ ๊ฐ™๋‹ค๋ฉด, ๋ชฉํ‘œ ๋ฐฐ์—ด์„ ์™„์„ฑํ–ˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•˜๋ฏ€๋กœ true๋ฅผ ๋ฐ˜ํ™˜
  • ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด, ํ˜„์žฌ idxGoal ์œ„์น˜์˜ goal ๋‹จ์–ด์™€ cards1 ๋˜๋Š” cards2์˜ ๋‹จ์–ด๊ฐ€ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ, ํ•ด๋‹น ์นด๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œ์ผœ ๋‹ค์Œ ๋‹จ์–ด๋กœ ์žฌ๊ท€ ํ˜ธ์ถœํ•œ๋‹ค.

๐Ÿ”” ๋Š๋‚€์ 

  • ์žฌ๊ท€ํ•จ์ˆ˜๋งŒ๋“ค ๋•Œ ์•„์ง ์–ด๋–ป๊ฒŒ ๊ตฌ์กฐ์งœ์•ผํ•˜๋Š”์ง€ ๊ฐ์ด ์•ˆ์žกํ˜€์„œ ๊ตฌ๊ธ€๋ง ํ›„ ์—ฌ๋Ÿฌ ๊ตฌ์กฐ๋ฅผ ์ฐธ๊ณ ํ–ˆ๋‹ค. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์“ฐ์ง€ ์•Š๊ณ ๋„ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ๋„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.
  • ์ข€ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์งœ๊ณ  ์‹ถ๋‹ค..
๋ฐ˜์‘ํ˜•
Comments