【LeetCode】526. Beautiful Arrangement【M】【35】【回溯】


Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 ≤ i ≤ N) in this array:

  1. The number at the ith position is divisible by i.
  2. i is divisible by the number at the ith position.

Now given N, how many beautiful arrangements can you construct?

Example 1:

Input: 2
Output: 2
Explanation: 

The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.

Note:

  1. N is a positive integer and will not exceed 15.

Subscribe to see which companies asked this question.


对每个位置,判断是不是能够整除

现在问题是,被注释掉的只是一个普通的广搜,并是不回溯,n=10的时候,超时了

后面是回溯的算法。

现在的一个需要注意的是,对于回溯问题,有一种方式就是,其中是否访问过,可以用visited标记,而不是用数字一个个塞进去



class Solution(object):
    def countArrangement(self, N):
            
        '''        
        def check(num):
            #print 'check',num
            for i in range(len(num)):
                if num[i] % (i+1) != 0 and (i+1) % num[i] != 0:
                    return 0
            return 1

        def bt(pos,res,n,num):
            if pos == n:
                res += check(num)
                return res
            for i in xrange(0,pos+1):
                temp = num[:i]+[pos+1]+num[i:]
                res = bt(pos+1,res,n,temp)
            return res
        return bt(1,0,N,[1])
        '''
        
        
        self.res = 0
        def bt(N,pos,visited):
            if pos > N:
                self.res += 1
                #print self.res
                return 
            for i in xrange(1,N+1):
                #print i,N+1
                if visited[i] == 0 and (i % pos == 0 or pos % i == 0):
                    #print i,N,pos,visited,self.res
                    visited[i] = 1
                    bt(N,pos+1,visited)
                    visited[i] = 0
            
            
            
        bt(N,1,[0]*(N+1))
        return self.res
        
        
        
        
        """
        :type N: int
        :rtype: int
        """


猜你喜欢

转载自blog.csdn.net/sscssz/article/details/68924050