Problem
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:
The number at the ith position is divisible by i.
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:
N is a positive integer and will not exceed 15.
class Solution { int count = 0; public int countArrangement(int N) { //for each position, fill with 1-N using dfs //when position moved to N+1, we found another arrangement boolean[] used = new boolean[N+1]; dfs(1, N, used); return count; } private void dfs(int index, int len, boolean[] used) { if (index > len) { count++; return; } for (int i = 1; i <= len; i++) { if (!used[i] && (i%index == 0 || index%i == 0)) { used[i] = true; dfs(index+1, len, used); used[i] = false; } } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72234.html
摘要:用的思想,加上题目的特殊意思,来解决问题。如果个数字,有种结果。这里对原题多加了一个输出的要求,代码如下。也是为了去重,两个分解的解法是对称的,乘法对称的重点就是 用combination的思想,加上题目的特殊意思,来解决问题。 526 Beautiful Arrangement Suppose you have N integers from 1 to N. We define a ...
找出string里的单词。 186. Reverse Words in a String II, 434. Number of Segments in a String combination类型题 77. Combinations 39. Combination Sum 40. Combination Sum II 216. Combination Sum III 494. Target S...
摘要:如果当前数字代表的整数值已经是所有排列组合中的最大值,则返回当前数字组成的最小值。可是这意味着大量无用的数字的生成和比较。一个数字中的各个位上的数如何调整顺序才能获得一个最小的更大值。其次,要保证移动之后,高位以后的值为最小值。 题目要求 Implement next permutation, which rearranges numbers into the lexicographi...
摘要:我们所找到的这个元素就是排序需要改变的第一个元素。然后我们选取一个刚好大于此元素的数,与当前元素进行替换。并对后面的所有元素重新按照升序排列就可以得到最终的答案。 题目详情 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of...
摘要:因为增加高位会带来更大的增益。所以对于一个长为的序列,我们增加第位的前提是,前位已经达到了最大排列方法。因为是找下一个数,所以我们要找一个比小却尽可能大的数,所以找到。把换到的位置后,后三位仍然是个降序的排列。 Next Permutation Implement next permutation, which rearranges numbers into the lexicogr...
阅读 2537·2023-04-25 20:05
阅读 2873·2023-04-25 17:56
阅读 2174·2021-10-14 09:49
阅读 2655·2019-08-29 15:10
阅读 2879·2019-08-29 12:25
阅读 399·2019-08-28 18:23
阅读 721·2019-08-26 13:26
阅读 1348·2019-08-23 18:21