总觉得有陷阱,小心翼翼地做完发现是E难度的。。
正统做法就backtrack,注意break case..
一开始我觉得明显可以列举出所有可能,反正一天就12*60,这才多少。。
backtrack
public class Solution
{
public List<String> readBinaryWatch(int num)
{
List<String> res = new ArrayList<String>();
if(num == 0)
{
res.add("0:00");
return res;
}
lights(res,new int[10],0,0,num);
return res;
}
public void lights(List<String> res, int[] temp,int index,int curNum, int left)
{
if(curNum == left)
{
generate(res,temp);
}
else
{
for(int i = index; i < 10;i++)
{
int[] tempArray = temp.clone();
tempArray[i]++;
lights(res,tempArray,i+1,curNum+1,left);
}
}
}
public void generate(List<String> res, int[] temp)
{
int hours = temp[0]*8 + temp[1]*4 + temp[2]*2 + temp[3];
if(hours > 11) return;
int mins = temp[4] * 32 + temp[5]*16 + temp[6]*8 + temp[7]*4 + temp[8]*2 + temp[9];
if(mins > 59) return;
String hStr = new String(Integer.toString(hours));
String mStr = new String();
if(mins < 10) mStr += "0";
mStr += Integer.toString(mins);
res.add(hStr + ":" + mStr);
return;
}
}
Stefanpochmann用的枚举,就是第二种。
不过人家的枚举写出来简洁美观
public List<String> readBinaryWatch(int num) {
List<String> times = new ArrayList<>();
for (int h=0; h<12; h++)
for (int m=0; m<60; m++)
if (Integer.bitCount(h * 64 + m) == num)
times.add(String.format("%d:%02d", h, m));
return times;
}