Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหาเวลาที่ใกล้ที่สุดจากการนำตัวเลขเดิมมาใช้ซ้ำใน Python


มีเวลา 24 ชั่วโมง "hh:mm" หาเวลาถัดไปที่ใกล้ที่สุดที่จัดจากตัวเลขเดิมได้ (ใช้ซ้ำได้ไม่จำกัด)

เช่น s="03:15" ให้ "03:30"

ขั้นตอนการแก้ปัญหา

  • เก็บตัวเลข 4 ตัวใน use
  • Backtracking สร้างเวลาที่เป็นไปได้ทั้งหมด (ตรวจสอบชั่วโมง 0-23, นาที 0-59)
  • เรียงเวลาทั้งหมด หาเวลาถัดไปของ s ถ้าไม่มีคืนเวลาแรก (วันถัดไป)

ตัวอย่างโค้ด

class Solution:
    def solve(self, s):
        use = [s[0], s[1], s[3], s[4]]
        possible = set()
        def backtrack(path):
            nonlocal possible, use
            if len(path) == 4:
                possible.add(path[:2] + ":" + path[2:])
                return
            for p in use:
                if not (len(path)==0 and p>"2") and not (path=="2" and p>"3") and not (len(path)==2 and p>"5"):
                    backtrack(path+p)
        backtrack("")
        possible = sorted(possible)
        for i in range(len(possible)-1):
            if possible[i] == s: return possible[i+1]
        return possible[0]

ob = Solution()
s = "03:15"
print(ob.solve(s))

อินพุต

"03:15"

เอาต์พุต

03:30