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;
        }
    };
    
  • 相关阅读:
    日志记录到txt文件
    使用NuGet安装EntityFramework4.2
    Redis 安装与简单示例 <第一篇>
    时间加减时间段(年、月、日、分、秒)
    控件属性设置
    window.showModalDialog 与window.open传递参数的不同?
    如何进行js动态生成option?如何实现二级连动?
    System.Data.SqlClient.SqlError: 备份集中的数据库备份与现有的 'XXX' 数据库不同
    如何激发手机的高分辨率
    PHP--正则表达式和样式匹配--小记
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3954256.html
Copyright © 2011-2022 走看看