码迷,mamicode.com
首页 > 其他好文 > 详细

52. Sort Colors && Combinations

时间:2014-09-03 18:06:26      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   ar   for   

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.

Note: You are not suppose to use the library‘s sort function for this problem.

click to show follow up.

Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0‘s, 1‘s, and 2‘s, then overwrite array with total number of 0‘s, then 1‘s and followed by 2‘s.

Could you come up with an one-pass algorithm using only constant space?

思路: 1. 类似快排,走两遍(v=1, 分出0;v = 2,分出1)。

void partition(int A[], int n, int v) {
    int start = 0, end = n-1;
    while(start < end) {
        while(start < end && A[start] < v) ++start;
        while(start < end && A[end] >= v) --end;
        int tem = A[start];
        A[start++] = A[end];
        A[end--] = tem;
    }
}
class Solution {
public:
    void sortColors(int A[], int n) {
        partition(A, n, 1);
        partition(A, n, 2);
    }
};

 2. 计数排序。计数与重写。

class Solution {
public:
    void sortColors(int A[], int n) {
        int count[3] = {0};
        for(int i = 0; i < n; ++i) count[A[i]]++;
        int id = 0;
        for(int i = 0; i < 3; ++i) 
            for(int j = 0; j < count[i]; ++j) 
                A[id++] = i;
    }
};

 

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],
]

思路:递归,每层从前往后逐步取元素。
void combination(int k, int num, int begin, int end, vector<int> & vec2, vector<vector<int> > &vec) {
    if(num == k) {
        vec.push_back(vec2);
        return;
    }
    for(int i = begin; i <= end; ++i) {
        vec2.push_back(i);
        combination(k, num+1, i+1, end, vec2, vec);
        vec2.pop_back();
    }
}

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<int> vec2;
        vector<vector<int> > vec;
        combination(k, 0, 1, n, vec2, vec);
        return vec;
    }
};

 

 

52. Sort Colors && Combinations

标签:style   blog   http   color   os   io   strong   ar   for   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3954256.html

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