剑指offer-和为S的连续正数序列之python实现

class Solution:
    def FindContinuousSequence(self, tsum):
        if tsum < 3:                                
            return []                               
        if tsum == 3:                               
            return [[1, 2]]                           
        left = 1                                    
        right = 2                                   
        res = []                                    
        temp = []                                   
        total = 3                                   
        while right <= int((tsum + 1) / 2):         
            if total > tsum:                        
                total = total - left                
                left = left + 1                     
                                               
            elif total < tsum:                      
                right = right + 1                   
                total = total + right               
            else:                                   
                for i in range(left, right + 1):    
                    temp.append(i)                  
                res.append(temp)                    
                temp = []                           
                left = left + 1      
                right = left + 1     
                total = left + right                 
        return res

猜你喜欢

转载自blog.csdn.net/Sallywa/article/details/89423339