zoukankan      html  css  js  c++  java
  • 52. Sort Colors && Combinations

    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;
        }
    };
    
  • 相关阅读:
    冒泡排序
    希尔排序
    现实中遇到的业务状况记录
    OneZero第二周第二次站立会议(2016.3.29)
    OneZero第二周第一次站立会议(2016.3.28)
    OneZero第五次站立会议(2016.3.25)
    OneZero第四次站立会议(2016.3.24)
    PSP(3.16——3.22)以及周记录
    OneZero第三次站立会议(2016.3.23)
    读“软工实践总结作业”有感
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3954256.html
Copyright © 2011-2022 走看看