Swift solution - Backtracking


  • 0
    class Solution {
        func readBinaryWatch(_ num: Int) -> [String] {
            var result = [String]()
            let nums1 = [8, 4, 2, 1]
            let nums2 = [32, 16, 8, 4, 2, 1]
            
            for i in 0...num {
                let list1 = generateDigit(nums1, i)
                let list2 = generateDigit(nums2, num - i)
                for num1 in list1 {
                    if num1 >= 12 {
                        continue
                    }
                    for num2 in list2 {
                        if num2 >= 60 {
                            continue
                        }
                        result.append(String(num1) + ":" + (num2 < 10 ? ("0" + String(num2)) : String(num2)))
                    }
                }
            }
            
            return result
        }
        
        private func generateDigit(_ nums: [Int], _ count: Int) -> [Int] {
            var result = [Int]()
            helper(nums, count, 0, 0, &result)
            return result
        }
        
        private func helper(_ nums: [Int], _ count: Int, _ pos: Int, _ sum: Int, _ result: inout [Int]) {
            if count == 0 {
                result.append(sum)
                return
            }
            
            for i in pos..<nums.count {
                helper(nums, count - 1, i + 1, sum + nums[i], &result)
            }
        }
    }
    

Log in to reply
 

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