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; } } } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 2557·2023-04-25 20:05
閱讀 2886·2023-04-25 17:56
閱讀 2195·2021-10-14 09:49
閱讀 2681·2019-08-29 15:10
閱讀 2922·2019-08-29 12:25
閱讀 416·2019-08-28 18:23
閱讀 757·2019-08-26 13:26
閱讀 1370·2019-08-23 18:21