Suppose you have n
integers labeled 1
through n
. A permutation of those n
integers perm
(1-indexed) is considered a beautiful arrangement if for every i
(1 <= i <= n
), either of the following is true:
perm[i]
is divisible byi
.i
is divisible byperm[i]
.
Given an integer n
, return the number of the beautiful arrangements that you can construct.
Example 1:
Input: n = 2 Output: 2 Explanation: The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1
Example 2:
Input: n = 1 Output: 1
Constraints:
1 <= n <= 15
优美的排列。
假设有从 1 到 N 的 N 个整数,如果从这 N 个数字中成功构造出一个数组,使得数组的第 i 位 (1 <= i <= N) 满足如下两个条件中的一个,我们就称这个数组为一个优美的排列。条件:
第 i 位的数字能被 i 整除
i 能被第 i 位上的数字整除
现在给定一个整数 N,请问可以构造多少个优美的排列?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/beautiful-arrangement
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是backtracking。既然这个所谓的优美的排列是需要试探所有的数字的,所以用backtracking是比较合适的。
时间O(k) - 一共有N个数字但是只有K种排列
空间O(n) - 回溯用到的栈空间
Java实现
1 class Solution { 2 int count = 0; 3 4 public int countArrangement(int n) { 5 boolean[] visited = new boolean[n + 1]; 6 helper(n, 1, visited); 7 return count; 8 } 9 10 private void helper(int n, int start, boolean[] visited) { 11 if (start > n) { 12 count++; 13 return; 14 } 15 for (int i = 1; i <= n; i++) { 16 if (!visited[i] && (start % i == 0 || i % start == 0)) { 17 visited[i] = true; 18 helper(n, start + 1, visited); 19 visited[i] = false; 20 } 21 } 22 } 23 }