題目連接:https://leetcode.com/problems...java
又是一道不像easy的題。。
首先是窮舉,把小時從0到11,和分鐘從0到59全部的可能窮舉一遍,1的數量等於num時就加入結果。 參考discussion裏的:
https://discuss.leetcode.com/...ide
backtracking是能夠作的,分開考慮小時和分鐘,分別作dfs,而後合在一塊兒。參考discussion裏面。
https://discuss.leetcode.com/...
注意hour至多4位,minute至多6位,因此i <= 4, num - i <= 6,h要小於12,m要小於60。idea
public class Solution { public List<String> readBinaryWatch(int num) { List<String> result = new ArrayList(); if(num < 0 || num > 10) return result; for(int i = Math.max(0, num-6); i <= Math.min(num, 4); i++) { List<Integer> hours = new ArrayList(); dfs(hours, 0, i, 0, hour); List<Integer> minutes = new ArrayList(); dfs(minutes, 0, num - i, 0, minute); for(int h : hours) { if(h >= 12) continue; for(int m : minutes) { if(m > 59) continue; result.add(String.format("%d:%02d", h, m)); } } } return result; } int[] hour = {1, 2, 4, 8}; int[] minute = {1, 2, 4, 8, 16, 32}; private void dfs(List<Integer> time, int index, int light, int cur, int[] num) { if(light == 0) { time.add(cur); return; } if(index == num.length) return; for(int i = index; i < num.length; i++) { dfs(time, i + 1, light - 1, cur + num[i], num); } } }