欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 401. Binary Watch

程序员文章站 2022-05-20 23:12:46
...

题目简述:
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).
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

算法思路:
设 i 个小时的bit亮,n-i个分钟的bit亮,分别算出i个bit的若干种组合和n-i个bit的若干种组合,将这2个组合得到的结果合并就可以得到时刻了,i 从0到n。

提交结果:
Runtime: 2 ms, faster than 79.31% of Java online submissions for Binary Watch.

参考代码:

public static List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<String>();
        int[] hour = {1,2,4,8};
        int[] min = {1,2,4,8,16,32};
        for(int i=0;i<=num;i++){
			List<String> resHour = new ArrayList<String>();
			List<String> resMin = new ArrayList<String>();
			List<Integer> temp = new ArrayList<Integer>();
			//找到小时的组合
			findHour(hour, resHour, 0, i, temp);
			temp.clear();
			//找到分钟的组合
			findMin(min, resMin, 0, num - i, temp);
			// 时与分组合成时刻
			for (int j = 0; j < resHour.size(); j++) {
				for (int k = 0; k < resMin.size(); k++) {
					result.add(resHour.get(j) + ":" + resMin.get(k));
				}
			}
        }
        return result;
    }
    public static void findHour(int[] hour,List<String> result,int index,int count,List<Integer> temp){
    	if(count==temp.size()){
    		int sum=0;
    		for(Integer key:temp)
    			sum += key;
    		//最大11时
    		if(sum<=11)
    			result.add(String.valueOf(sum));
    		return; 		
    	}
    	for(int i=index;i<hour.length;i++){
    		temp.add(hour[i]);
    		findHour(hour, result, i+1, count, temp);
    		//恢复 findHour()之前的样子,尝试找下一个元素
    		temp.remove(temp.size()-1);
    	}
    }
    public static void findMin(int[] min,List<String> result,int index,int count,List<Integer> temp){
    	if(count==temp.size()){
    		int sum=0;
    		for(Integer key:temp)
    			sum += key;
    		//最大59分钟
    		if(sum<=59){
    			if(sum<=9)   				
    				result.add('0'+String.valueOf(sum));
    			else
    				result.add(String.valueOf(sum));
    		}
    		return; 		
    	}
    	for(int i=index;i<min.length;i++){
    		temp.add(min[i]);
    		findMin(min, result, i+1, count, temp);
    		temp.remove(temp.size()-1);
    	}
    }
相关标签: 回溯