2016-10-16 4 views
0

바이너리 시계의 여러 표시등이 나타낼 수있는 모든 시간 값을 반환하는 알고리즘을 작성하려고합니다. https://leetcode.com/problems/binary-watch/바이너리 시계 알고리즘 (Java)

public class Solution { 
public List<String> readBinaryWatch(int num) { 
    List<String> result = new ArrayList<String>(); 
    int[] time = new int[] {1, 2, 4, 8, 1, 2, 4, 8, 16, 32}; 

    helper(result, time, num, 0, 0, 0); 

    return result; 
} 

public void helper(List<String> result, int[] time, int num, int start, int hour, int minute){ 
    if (num == 0){ 
     if (hour < 11 && minute < 59){ 
      String x = "" + hour + ":"; 
      if (minute < 10){x = x + "0";} 
      x = x + minute; 
      result.add(x); 
     } 
    } else { 
     for (int i = start; i < time.length; i++){ 
      int h, m; 
      if (i >= 4){h = hour; m = minute + time[i];} else {h = hour + time[i]; m = minute;} 
      helper(result, time, num - 1, start + 1, h, m); 
     } 
    } 

}} 

내 솔루션은 테스트 케이스의 일부를 실패하는 것, 그리고 난 그냥 이유를 알아낼 수 없습니다 세부

전체 문제는 여기에서 찾을 수 있습니다. 제안?

+1

귀하의 범위 체크가 잘못된 것 같다 코드는 "1시 59분"을 "11시"같은 솔루션을 제공하거나 않습니다 –

답변

1

항상 [i] 시간을 걸리는 옵션을 건너 뜁니다. 또한, 왜 당신은 사용하고 있습니까? 중 하나를하는 것은 시간이 걸릴 선택 [시작] 여부 - 두 개의 재귀 호출 :

public void helper(List<String> result, int[] time, int num, int start, int hour, int minute){ 
    if (start == time.length && num > 0) 
     return; 

    if (num == 0){ 
     if (hour <= 12 && minute <= 59){ 
      String x = "" + hour + ":"; 
      if (minute < 10){x = x + "0";} 
      x = x + minute; 
      result.add(x); 
     } 
    } else { 
     helper(result, time, num, start + 1, hour, minute); 
     int h, m; 
     if (start >= 4){h = hour; m = minute + time[start];} else {h = hour + time[start]; m = minute;} 
     helper(result, time, num - 1, start + 1, h, m); 
    } 
}