최대 1 분 소요


  • 2,3중 반복문 작동 방식 이해하기
  • 재귀함수 복습 및 이해하기

3중 반복문 작동 방식

class BlackJack {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};

        for(int i=0; i<nums.length;i++){
            for(int j=i+1; j<nums.length; j++){
                for(int k=j+1; k<nums.length; k++){
                    System.out.println("k = "+k);
                }
                System.out.println("jj = "+j);
            }
            System.out.println("iiii = "+i);
        }
    }
}

출력
k = 2
k = 3
jj = 1
k = 3
jj = 2
jj = 3
iiii = 0
k = 3
jj = 2
jj = 3
iiii = 1
jj = 3
iiii = 2
iiii = 3

재귀함수 작동 방식

public class Solution { 
	public ArrayList<String[]> rockPaperScissors(int rounds) {
    ArrayList<String[]> outcomes = new ArrayList<>();
    return permutation(rounds, new String[]{}, outcomes);
  }

  public ArrayList<String[]> permutation(int roundsToGo, String[] playedSoFar, ArrayList<String[]> outcomes) {

    if(roundsToGo == 0) {   // 탈출문
      outcomes.add(playedSoFar);   
      return outcomes;
    }

    String[] rps = new String[]{"rock", "paper", "scissors"};

    for(int i = 0; i < rps.length; i++) { // 재귀 탈줄문 작동시 i++, 다시 재귀 시작

      String currentPlay = rps[i];

      String[] concatArray = Arrays.copyOf(playedSoFar, playedSoFar.length + 1);  
      concatArray[concatArray.length - 1] = currentPlay;

      outcomes = permutation(roundsToGo - 1, concatArray, outcomes); //재귀 
    }

    return outcomes;
  }
}

카테고리: ,

업데이트:

댓글남기기