1 Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
这里只有3个数进行排序,我们可以采用两指针方法,遍历数组,遇到红色时与头指针交换数据,头指针加1,遇到蓝色时与尾指针交换数据,尾指针减1,遍历直到遇到尾指针时结束。
void sortColors(vector<int>& nums) {
int len = nums.size();
int begin = 0, end = len - 1;
for (int i = 0; i<len; i++)
{
if (i>end) return;
if (nums[i] == 0)
{
swap(nums[i], nums[begin]);
begin++;
}
else if (nums[i] == 2)
{
swap(nums[i], nums[end]);
end--;
i--;
}
}
}
2 Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.For example,If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
从n个数中选取k个数的组合,我们可以选出1,再从2到n中选出k-1个数;,选出2,再从3到n中选出k-1个数;以此方法得到所有的组合。
void combinedst(int n,int k,int level, vector<int> &res,vector<vector<int>> &result)
{
if(res.size() == k)
{
result.push_back(res);
return;
}
for(int i = level; i<=n; i++)
{
res.push_back(i);
combinedst(n,k,i+1,res,result);
res.pop_back();
}
}
vector<vector<int>> combine(int n, int k)
{
vector<int> res;
vector<vector<int> > result;
if(n<k||k<=0) return result;
combinedst(n,k,1,res,result);
return result;
}
时间: 2024-11-05 14:43:41