526 Beautiful Arrangement

使用回溯的思想,对于数组进行处理。

class Solution(object):
    def __init__(self):
        self.ans = 0

    def helper(self, cnt, used, remain):  
        if remain == 0:
            self.ans += 1
        else:
            v = cnt + 1
            for i in range(1, len(used)):
                if used[i] == False and (i % v == 0 or v % i == 0):
                    used[i] = True
                    self.helper( v, used, remain - 1)
                    used[i] = False

    def countArrangement(self, N):
        """
        :type N: int
        :rtype: int
        """
        self.helper(0, [False for i in range(N+1)], N)
        return self.ans

results matching ""

    No results matching ""