码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode的medium题集合(C++实现)十四

时间:2015-05-26 10:46:21      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   递归   两指针   

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;
    }

LeetCode的medium题集合(C++实现)十四

标签:c++   leetcode   递归   两指针   

原文地址:http://blog.csdn.net/zhulong890816/article/details/46004153

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!