java recursion solution


  • 0
    P
    public class Solution {
        List<String> list = new ArrayList<>();
        int num;
        int[] allset = {1,2,4,8,1,2,4,8,16,32};
        int count = 0;
        public List<String> readBinaryWatch(int num) {
            this.num = num;
            helper(0,0,0);
            //Collections.sort(list);
            return list;
        }
        private void helper(int index,int hour,int minute)
        {
            if(count == num)
            {
                //System.out.println("hour = "+hour+" minute = "+minute);
                StringBuilder sb = new StringBuilder();
                if(hour >= 12||minute >= 60)
                {
                    return;
                }
                if(hour!=0)
                {
                    sb.append(hour);
                }
                else
                {
                    sb.append("0");
                }
                sb.append(":");
                if(minute!=0)
                {
                    if(minute<10)
                    {
                        sb.append("0");
                        sb.append(minute);
                    }
                    else
                    {
                        sb.append(minute);
                    }
                }
                else
                {
                    sb.append("00");
                }
                list.add(sb.toString());
                return;
            }
            for(int i = index;i<allset.length;i++)
            {
                count++;
                if(i<4)
                {
                    hour+=allset[i];
                }
                else
                {
                    minute+=allset[i];
                }
                helper(i+1,hour,minute);
                if(i<4)
                {
                    hour-=allset[i];
                }
                else
                {
                    minute-=allset[i];
                }
                count--;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.