力扣,https://leetcode.cn/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/description/
依旧是使用双指针思想!!!
class Solution {
public int[][] fileCombination(int target) {
List<int[]> res = new ArrayList<>();
int left = 1, right = 2, curSum = 3;
while (left < right) {
if (curSum < target) {
curSum += ++right;
} else if (curSum > target) {
curSum -= left++;
} else {
int[] tmp = new int[right - left + 1];
for (int i = left; i <= right; ++i) {
tmp[i - left] = i;
}
res.add(tmp);
curSum += ++right;
}
}
int[][] resArray = new int[res.size()][];
for (int i = 0; i < resArray.length; ++i) {
resArray[i] = res.get(i);
}
return resArray;
}
}
##Solution1:我的答案
基本思路是根据等差数列的前n项和推导出首项与项数的关系,设首项为
a
1
a_1
a1,项数为
k
k
k,和为
S
S
S,则有
S
=
(
a
1
+
a
1
+
k
−
1
)
k
2
S=\frac{(a_1+a_1+k-1)k}{2}
S=2(a1+a1+k−1)k
a
1
=
2
S
+
k
−
k
2
2
k
a_1=\frac{2S+k-k^2}{2k}
a1=2k2S+k−k2
对
k
k
k从1到
S
S
S遍历,找到所有的答案。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int> > res;
vector<int> temp;
int a = 0, start = 0;
for(int k = 2; k <= sum; k++){
a = 2 * sum + k - k * k;
if( a > 0 && a % (2 * k) == 0) {
for(int i = a/(2*k); i <= a/(2*k) + k - 1; i++)
temp.push_back(i);
res.push_back(temp);
temp.clear();
}
}
sort(res.begin(),res.end(),my_cmp);
return res;
}
// 序列越长,开始的数字就越小啊!没毛病!
static bool my_cmp(vector<int> a, vector<int> b) {
if(a.size() >= b.size())
return true;
else
return false;
}
};
##意外收获:
因为要求序列按首个数字从小到大排列,所以需对res中的vector按长度从长到短排序,利用sort()函数可以定义自己的排序规则可以实现这一步。注意:在类内定义自己的比较函数时一定要声明为static的,否则会报错。
关于sort()函数的用法,参加该博客:
https://www.cnblogs.com/nihow/p/4297102.html
C++中sort的比较函数写法,有需要的朋友可以参考下。
定义排序函数:
方法1:声明外部比较函数
bool Less(const Student& s1, const Student& s2) {
return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);
注意:比较函数必须写在类外部(全局区域)或声明为静态函数
当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。
否则,会出现错误.
方法2:重载类的比较运算符
bool operator<(const Student& s1, const Student& s2) {
return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end());
方法3:声明比较类
struct Less {
bool operator()(const Student& s1, const Student& s2) {
return s1.name < s2.name; //从小到大排序
}
};
std::sort(sutVector.begin(), stuVector.end(), Less());