[关闭]
@LIUHUAN 2019-06-30T11:25:31.000000Z 字数 1992 阅读 941

动态规划之实际问题

algorithm


两个操作的键盘

思路1

  1. int minSteps(int n) {
  2. vector<int> dp( n + 1 , 0);
  3. for(int i = 2; i<= n; i++ ) {
  4. dp[i] = i;
  5. int m = i / 2;
  6. for(int j = 1; j <= m; j++ ) {
  7. if(i % j == 0 ) {
  8. int c = i / j - 1;
  9. c += 1;
  10. dp[i] = min(dp[i],dp[j] +c );
  11. }
  12. }
  13. }
  14. return dp[n];
  15. }

broken-calculator

  1. int brokenCalc(int X, int Y) {
  2. if( X == Y )
  3. return 0;
  4. if( X > Y )
  5. return X - Y;
  6. if(Y & 0x01 ) {
  7. return brokenCalc(X, Y + 1 ) + 1 ;
  8. }else {
  9. return brokenCalc(X, Y / 2 ) + 1;
  10. }
  11. return 0;
  12. }

构成三角形的个数

题目大意

分析

思路1

  1. int triangleNumber(vector<int>& nums) {
  2. int count = 0;
  3. for (int i = 0; i < nums.length - 2; i++) {
  4. for (int j = i + 1; j < nums.length - 1; j++) {
  5. for (int k = j + 1; k < nums.length; k++) {
  6. if (sum2judge(nums,i,j,k) && sum2judge(nums,i,k,j) && sum2judge(nums,j,k,i))
  7. count++;
  8. }
  9. }
  10.        } I
  11.        return count;
  12. }
  13. int sum2judge(vector<int>& nums, int i,int j,int k) {
  14. return nums[i] + nums[j] > nums[k];
  15. }

思路2

  1. int triangleNumber(vector<int>& nums) {
  2. sort(nums.begin(),nums.end());
  3. int n = nums.size();
  4. int sum = 0;
  5. for( int i = 0 ;i < n; i++ ) {
  6. for( int j = i + 1;j < n; j++ ) {
  7. int u = nums[i] + nums[j] - 1;
  8. auto hi = upper_bound(nums.begin() + j + 1, nums.end(), u);
  9. int c = hi - (nums.begin() + j + 1);
  10. if ( c > 0 ) {
  11. sum += c;
  12. }
  13. }
  14. }
  15. return sum;
  16. }

思路3

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注