LeetCode[526]Beautiful Arrangement(Java)
来源:互联网 发布:java专业技能 编辑:程序博客网 时间:2024/06/05 03:32
Description:
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: 2Output: 2Explanation:
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.
Solution:
Backtracing(回溯法)
回溯法是暴力求解的优化,在遍历所有情况的过程中,一旦出现不符合要求的情况,则将该次遍历终止。将不能的解尽早舍弃。
设置一个递归函数,函数的参数携带当前解的信息,根据这些参数判断当前情况是可能解(记录或打印结果)或者不能解(回溯)。
class Solution { int result = 0; public int countArrangement(int N) { boolean[] visited = new boolean[N + 1]; count(N, 1, visited); return result; } public void count(int N, int current, boolean[] visited){ if(current > N){ result++; return; } for(int i = 1; i <= N; i++){ if(!visited[i] && (current % i == 0 || i % current == 0)){ visited[i] = true; count(N, current + 1, visited); visited[i] = false; } } }}
阅读全文
0 0
- LeetCode[526]Beautiful Arrangement(Java)
- Leetcode 526 Beautiful Arrangement
- LeetCode 526 Beautiful Arrangement
- Leetcode Beautiful Arrangement
- LeetCode 526. Beautiful Arrangement
- 【Leetcode】526. Beautiful Arrangement
- [LeetCode]526. Beautiful Arrangement
- 【LeetCode】526. Beautiful Arrangement
- leetcode 526. Beautiful Arrangement
- Leetcode: 526. Beautiful Arrangement
- [LeetCode] 526. Beautiful Arrangement
- [LeetCode]526. Beautiful Arrangement
- leetcode- Beautiful Arrangement II
- [LeetCode] 526. Beautiful Arrangement
- LeetCode:526. Beautiful Arrangement
- leetcode练习 Beautiful Arrangement
- [leetcode] 526. Beautiful Arrangement
- leetCode-Beautiful Arrangement II
- java递归生成树
- 全面理解面向对象的 JavaScript
- SPFA模板
- 51nod 1053 最大M子段和 V2 (链表 对经典dp进行优化)
- 架构模式(Architectural Pattern)、设计模式(Design Pattern)、代码模式(Coding Pattern)
- LeetCode[526]Beautiful Arrangement(Java)
- Delphi ControlState和ControlStyle属性详解
- ElasticSearch搜索服务器-安装入门
- web前段对数据库执行的insert插入操作
- LintCode刷题——不同的路径 II
- offer17--合并两个有序链表
- Java中哪些异常必须声明并捕获,否则产生编译错误
- 帝国CMS7.2版多终端访问功能使用图文教程
- uva 12113 Overlapping Squares