Leetcode526. 回溯法之应用(一):统计数组排列数目
2017-09-30 08:14
423 查看
Leetcode526. Beautiful Arrangement
题目
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:
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.
解题分析
拿到这道题,可能第一想法就是找找规律,但很遗憾其实规律挺难找的。我们可以这样考虑,从最后一个数n出发,尝试将这个数与前面一个数进行交换,如果交换后的数组满足要求,就进一步进行交换。如果交换后不满足要求,就后退一步,将两个数交换回来。其实我上面描述的思想就是回溯法的思想。 回溯算法实际上是一个类似枚举的搜索尝试过程。其基本思想是,在包含问题的所有解的解空间树中,按照深度优先搜索的策略,从根结点出发深度探索解空间树。当探索到某一结点时,要先判断该结点是否包含问题的解,如果包含,就从该结点出发继续探索下去,如果该结点不包含问题的解,则逐层向其祖先结点回溯。
上面我就将最大的数字作为根节点,将其它数字作为其叶子节点。每往前访问一个数,就尝试将其与前面的数字交换,这其实就是探索的过程。如果交换后满足条件就继续往前交换,这就很类似深度优先探索了;如果不满足条件就交换回来,往祖先节点回溯。所以当根节点的所有子树都被访问也即遍历到最小的一个数时,这个过程就结束了,结果也就出来了。下面是这个算法的源代码。
源代码
class Solution { public: int number = 0; int countArrangement(int N) { int* nums = new int[N + 1]; for (int i = 0; i <= N; i++) { nums[i] = i; } count(nums, N); return number; } void count(int* nums, int n) { if (n == 0) { number 4000 ++; return; } for (int i = n; i > 0; i--) { swap(nums[i], nums ); if (nums % n == 0 || n % nums == 0) { count(nums, n - 1); } swap(nums , nums[i]); } } };
以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~
相关文章推荐
- leetcode 357. Count Numbers with Unique Digits 统计独特编码数组的数量 + 一个很简单的排列组合问题
- LeetCode Median of Two Sorted Arrays 在两个已排列的数组中找出中位数。时间复杂度为O(log(min(N,M))
- 数组应用实例(生成并打印随机数和统计随机数的分布)
- “全排列”问题系列(一)[LeetCode] - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题
- Leetcode22.+Leetcode216. 回溯法之应用(二):圆括号+组合问题
- poj Ping pong LA 4329 (树状数组统计数目)
- leetcode之深搜递归回溯类之排列与组合类-----77/39/40/216/317 组合 78/90/368 子排列 22/79/93/131 典型递归回溯 46/47 全排列
- 数组中有重复数据统计并按照次数的由大到小排列出来
- Leetcode39.+Leetcode491. 回溯法之应用(三):寻找组合和+求递增子数列
- Leetcode532. 找出数组中绝对值为k的数值对的数目
- 求全排列(数组有重复元素和数组无重复元素) 回溯 递归
- 减治法在生成全排列中的应用(JAVA)--回溯、Johnson-Trotter算法、自字典序
- Android统计应用内方法数目
- 减治法在生成全排列中的应用(JAVA)--回溯、Johnson-Trotter算法、自字典序
- 一维数组的应用-数组元素的倒序排列
- 05:统计单词数 [C语言字符数组的应用]
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- 第7章结构体数组应用举例之候选人票数统计
- leetcode 525. Contiguous Array 统计1和0相等最长子数组 + map统计index
- Java利用递归算法统计1-6的数组排列组合数