码迷,mamicode.com
首页 > 其他好文 > 详细

526. Beautiful Arrangement

时间:2017-10-24 22:59:40      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:this   return   use   时间   out   使用   color   方式   for   

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.

题目含义:假设你有1到N的N个整数,我们定义如果这N个整数可以组成数组后每 i 位(1 ≤ i ≤ N)都满足下面两个要求之一就称其为漂亮的安排:
  1. 第 i 个位置的数字可以被 i 整除。
  2. i 可以被第 i 个位置的数字整除。

现在给出N,你可以组成多少种漂亮的安排?

思路:

首先,初步尝试在随着N递增时寻找Beautiful 排列规律,发现并无明显的规律可寻,而且所有排列需要穷举才可找到。 
如果直接穷举递归,需要进行全排列,则算法的时间复杂度为O(n!),效率太低不可取。 
对于解决穷举问题,可以考虑使用回溯算法。回溯是递归的一种形式,可以用来解决是否有解、求所有解和求最优解的问题。简单来说,假设有一棵树,需要找到所有从树的根节点到叶节点的遍历方式,回溯算法会从根开始,然后选择一个根的节点,再从根的节点的节点进行选择,重复地进行直到找到一个叶节点,找到叶节点后会返回上一次遍历的节点寻找其他未遍历的其他节点,这样省去了重复的遍历过程,保证每次遍历都是新的。

根据回溯的思路,同样,可以对本题的Beautiful排列实现。比如,当N为5时,使用回溯算法先是得到(1,2,3,4,5)排列,符合要求,符合要求的排列数count+1,接着回溯到第四个位置,在剩下的选择中选5,但发现5不符合要求,然后跳过,不再往后判断。同样当得到(1,2,5)这前三个排列时,5已经不符合要求,也不会再往后判断(1,2,5,x,x)。这样减少了直接穷举递归方法中很多不需要判断操作,提高了效率。

具体来说,计算Beautiful排列的数量,可把长度为N的排列的位置看成结点,建立一个辅助类来记录所遍历结点的位置及在该位置符合要求的值,当结点的位置超过N长度则认为完成了一次Beautiful排列。

 

 1     int count = 0;
 2 
 3     public int countArrangement(int N) {
 4         if (N == 0) return 0;
 5         builtfulNumber(N, 1, new int[N + 1]);
 6         return count;
 7     }
 8 
 9     /***
10      *
11      * @param N 可以使用的最大整数
12      * @param pos  pos作为将被放置的数
13      * @param used 放置了数据的位置值为1
14      */
15     private void builtfulNumber(int N, int pos, int[] used) {
16         if (pos > N) {
17             count++;
18             return;
19         }
20 
21         for (int i = 1; i <= N; i++) {
22             if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) {
23                 //位置i上没有放置数据, 位置i可以被pos整除或者pos可以被位置i整除
24                 used[i] = 1; //位置i上放置了数据,
25                 builtfulNumber(N, pos + 1, used); //在下一个位置放置数据
26                 used[i] = 0; //位置i上撤销数据,准备i的下一个位置来循环
27             }
28         }
29     }

 

526. Beautiful Arrangement

标签:this   return   use   时间   out   使用   color   方式   for   

原文地址:http://www.cnblogs.com/wzj4858/p/7725600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!