开始我的算法学习之旅,刚开始自主学习,不够好请指出,多多益善
这边是我第一个独立完成的回朔,昨天晚上看了一会回朔和递归的概念,
这边还涉及到一点dfs…代码和题目本身不难,但是我还是犯了不少错误
class Solution {
static int []hours={1,2,4,8};
static int []mins={1,2,4,8,16,32};
public List<String> readBinaryWatch(int num) {
//回朔剪枝 1、时间大小 2、递推深度<需要点亮灯数目 不可取
List<String> time=new LinkedList<String>();
dfs(0,0,num,time,-1);
return time;
}
public static void dfs(int hour,int min,int index,List<String> time ,int depth)
{
if(index==0)
{
if(min<10)
time.add(hour+":0"+min);
else
time.add(hour+":"+min);
return;
}
depth++; //深度变化应该摆在起始
if(depth<4)
{
if((hour+hours[depth])<12)
dfs(hour+hours[depth],min,index-1,time,depth);
dfs(hour,min,index,time,depth);
}
else
{
if((min+mins[depth-4])<60)
dfs(hour,min+mins[depth-4],index-1,time,depth);
if(index<=9-depth)//假设还有三盏灯需要亮,却只有两次递推,不可取,9-depth表示还能最多递推次数
dfs(hour,min,index,time,depth);
}
}
}
这个很厉害,值得学习
https://blog.youkuaiyun.com/hy971216/article/details/81032969
Integer.toBinaryString(int)
Integer.bitCount(int )
String.format("%d:%02d", hour, min)