A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
- The order of output does not matter.
- The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
- The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
思路:进行back tracking 但是是二维的
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> list = new ArrayList<String>();
int[] hours = {1,2,4,8};
boolean[] hvisited = new boolean[hours.length];
int[] mins = {1,2,4,8,16,32};
boolean[] mvisited = new boolean[mins.length];
HashSet<String> hashset = new HashSet<String>();
collect(list,
hours, 0, 0, 0, hvisited,
mins, 0, 0, 0, mvisited,
num, hashset);
return list;
}
public void collect(List<String> list,
int[] hours, int hindex, int hnum, int hcount, boolean[] hvisited,
int[] mins, int mindex, int mnum, int mcount, boolean[] mvisited,
int num, HashSet<String> hashset) {
if(hcount + mcount == num) { //在满足条件的时候进行return
StringBuilder sb = new StringBuilder();
sb.append( hnum == 0 ? "0:" : hnum +":");
sb.append(mnum == 0 ? "00" : mnum >=10 ? mnum : "0"+mnum);
String res = sb.toString();
if(!hashset.contains(res) && hnum <=11 && mnum <= 59){
hashset.add(res);
list.add(res);
}
return;
}
for(int i=hindex; i<hours.length; i++){
for(int j=mindex; j<mins.length; j++){ //这里有两个for循环 进行二维的递归
if(!hvisited[i] ){
hvisited[i] = true;
hnum += hours[i];
hcount++;
if(hcount + mcount <= num){ //两个一维遍历相结合
collect(list, hours, i, hnum, hcount, hvisited, mins, j, mnum,mcount, mvisited, num, hashset);
}
hcount--; //完成一次调用之后 回到上一层 也就是回溯 back tracking
hnum -= hours[i];
hvisited[i] = false;
}
if(!mvisited[j]){
mvisited[j] = true;
mnum += mins[j];
mcount++;
if(hcount + mcount <= num){
collect(list, hours, i, hnum, hcount, hvisited, mins, j, mnum,mcount, mvisited, num, hashset);
}
mcount--;
mnum -= mins[j];
mvisited[j] = false;
}
}
}
}
}
有一种大神的做法,实在是好棒。逆向思维,学习学习。
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> list = new ArrayList<String>();
if(num < 0) return list;
for(int h=0; h<12; h++){
for(int m=0; m<60; m++){
if(Integer.bitCount(h) + Integer.bitCount(m) == num){
list.add(String.format("%d:%02d",h,m)); //%02d哇哦
}
}
}
return list;
}
}