摘要:用的思想,加上题目的特殊意思,来解决问题。如果个数字,有种结果。这里对原题多加了一个输出的要求,代码如下。也是为了去重,两个分解的解法是对称的,乘法对称的重点就是
用combination的思想,加上题目的特殊意思,来解决问题。
</>复制代码
526 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:
1.The number at the ith position is divisible by i.
2.i is divisible by the number at the ith position.
如果3个数字,有3种结果。
[1, 2, 3]
[2, 1, 3]
[3, 2, 1]
3
这里对Leetcode原题多加了一个输出的要求,代码如下。
</>复制代码
public Solution{
int count = 0;
public int countArrangement(int N) {
if (N == 0) return 0;
helper(N, 1, new int[N + 1], new ArrayList());
return count;
}
private void helper(int N, int pos, int[] used, List list) {
if (pos > N) {
count++;
System.out.println(list.toString());
return;
}
for (int i = 1; i <= N; i++) {
if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) {
used[i] = 1;
list.add(i);
helper(N, pos + 1, used, list);
list.remove(list.size()-1);
used[i] = 0;
}
}
}
}
</>复制代码
254 Factor Combinations
</>复制代码
比如给出的数字是12,质因数分解的结果如下:
[
[2, 6],
[2, 2, 3],
[3, 4]
]
</>复制代码
public class Solution {
public List> getFactors(int n) {
List> res = new ArrayList>();
if(n <= 3) return res;
dfs(n, res, new ArrayList(), -1);
return res;
}
public void dfs(int n, List> res, List path, int lower){
// 和一般combination不同的是,每一步都要导入到结果中。
if(lower != -1){
path.add(n);
res.add(new ArrayList<>(path));
path.remove(path.size()-1);
}
// lower 是为了解决重复分解的问题,比如12 = 2*2*3 = 3*2*2,但是后一个是重复的, 所以分解之后factor不能变小。
// upper 也是为了去重,12 = 3*4 = 4*3, 两个分解的解法是对称的,乘法对称的重点就是sqrt(n).
int upper = (int) Math.sqrt(n);
for(int i=Math.max(2, lower); i<= upper; i++){
if(n%i == 0){
path.add(i);
dfs(n/i, res, path, i);
path.remove(path.size()-1);
}
}
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66950.html
找出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...
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 ...
Problem Numbers can be regarded as product of its factors. For example, 8 = 2 x 2 x 2; = 2 x 4.Write a function that takes an integer n and return all possible combinations of its factors. Note: You ...
摘要:需求在里创建,然后通过代码消费。创建一个新的基于这个标准的创建一个因为我是在当前系统上的里调用当前系统提供的,所以选择当然这个的也是需要在这个地方自己创建一个的可以维护成给该创建的维护的将该的下载到本地。基于前一步创建的创建一个。 需求:在C4C UI里创建web service(maintain ticket),然后通过ABSL代码消费。1. 创建一个新的Communication ...
阅读 3715·2021-11-15 11:38
阅读 2866·2021-11-11 16:55
阅读 2663·2021-11-08 13:22
阅读 2845·2021-11-02 14:45
阅读 1412·2021-09-28 09:35
阅读 2800·2021-09-10 10:50
阅读 546·2019-08-30 15:44
阅读 2915·2019-08-29 17:06